Issue
I need to use the properties that I get inside .subscribe to update the HTML. I know that .subscribe is asynchronous so the value is undefined before it is resolved, but how can I make it wait until it has the value? At the moment I only get undefined for the object properties.
This is my service method where I call the API to fetch the data:
fetchCustomers(name: string) Observable<Customer[]> {
    return this.http.get<Customer>('MY URL')
}
and the component where I subscribe to it:
   customer: any;
   name: string;
  ngOnInit() {
    //this.name = /*code to retrieve the name*/
    this.renderCustomer(this.name)
  }
  renderCustomer(name) {
      this.testService.fetchCustomer(name).subscribe(data => {
      this.customer = data
  })
}
But when I call the method this.customer remains undefined. I need the properties of data to render  my HTML file like this:
 <tr> {{ customer.companyName }} </tr>
 <tr> {{ customer.fullName }} </tr>
 <tr> {{ customer.Email }} </tr>
How can I make this line this.customer = data to wait until the Observable is resolved? I have also tried this.customer = JSON.parse(JSON.stringify(data)) as it was suggested in another thread, but it did not work.
Solution
Your code looks right! Can you try using a safe navigation operator,
<tr> {{ customer?.companyName }} </tr>
<tr> {{ customer?.fullName }} </tr>
<tr> {{ customer?.Email }} </tr>
Answered By - Sajeetharan
 
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.