Load data when you have the variable loaded | Angular 7

1

I am consuming an API service in Node.JS and MongoDB this is the query.

this._productService.getProductById(productId).subscribe(
  response => {
    this.product = response['product'];
  },
  error => {
    console.log('Error');
  }
);

When the request is completed, the result value is saved in the product variable, but the web will render the content of that variable before the service enters the data returned by the backend, as it can tell you to wait for the service return the data and then show the data in the html? I have it that way in HTML.

{{product.name}}

But I get the following error.

ERROR TypeError: Cannot read property 'name' of undefined
at Object.eval [as updateDirectives] (ProductComponent.html:6)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:22477)
at checkAndUpdateView (core.js:21873)
at callViewAction (core.js:22114)
at execComponentViewsAction (core.js:22056)
at checkAndUpdateView (core.js:21879)
at callViewAction (core.js:22114)
at execEmbeddedViewsAction (core.js:22077)
at checkAndUpdateView (core.js:21874)
at callViewAction (core.js:22114)

And the ngOnInit () I have it that way.

  ngOnInit() {
this.url = GLOBAL.url;
this.categoryId = this._activatedRoute.snapshot.paramMap.get("category");
this.productId = this._activatedRoute.snapshot.paramMap.get("product");
this.getProductById(this.productId);

}

    
asked by Agustin Navarro 03.01.2019 в 11:10
source

1 answer

1

Angular has a syntax that allows you to solve this error in a simple way:

{{product?.name}}

This is the same as in simple Javascript would be

{{product == null ? '' : product.name}}

But it has the advantage that it can be easily linked:

{{a?.b?.c}} // muestra c si tanto a como b no son null o undefined
    
answered by 03.01.2019 / 12:33
source