In my ItemDetailComponent app, ItemDetailComponent information will be displayed. I have a service that retrieves all items using a promise. I use ActivatedRoute to retrieve the item id from the url, then start the service, get all the items, then find the item with the id obtained above and assign it to the selectedItem variable.
Here is the item-detail.component.ts :
export class ItemDetailComponent implements OnInit { private title = 'Item Details' private selectedItem: object constructor( private route: ActivatedRoute, private itemService: ItemService ) {} ngOnInit() { const selectedItemId = this.route.snapshot.params.itemId return this.itemService.getAllItems() .then((items) => { return _.find(items, item => item.itemId === selectedItemId) }) .then((selectedItem) => { this.selectedItem = selectedItem console.log('Inside promise', this.selectedItem) }) console.log('Outside promise', this.selectedItem) } }
And here is the item-detail.component.html template so that I can display my element, just an example:
<div> <h1>{{title}}</h1> <div *ngIf="selectedItem"> <div><label>Item ID: </label>{{selectedItem.itemId}}</div> </div> </div>
The application does not return anything except the name. Then I added two console.log() commands and found out that outside the promise, as well as the html template are displayed before the promise is fulfilled, and at the time there is no selectedItem . How to make the application fulfill them only after the promise is resolved to show the selectedItem for display?
EDIT . I added a new line to the html template for further study:
<div> <h1>{{title}}</h1> <div><label>Item ID 1: </label>{{selectedItem.itemId}}</div> <div *ngIf="selectedItem"> <div><label>Item ID 2: </label>{{selectedItem.itemId}}</div> </div> </div>
The application displays the label "Item ID 1:", but without the actual identifier. The console shows me an error saying that "It is not possible to read the" itemId "property from undefined, again confirming that the entire template is rendered before the promise is resolved and is not re-displayed after the data has been loaded. So strange.
source share