kachus22
kachus22

Reputation: 439

Angular 5 - Stop errors from undefined object before loading data

What's the best way to prevent errors in console from objects that are still undefined?

Let's say I have this

name : string;
constructor(private data: DataService) {
this.data.name.subscribe(res => this.name = res);
}

Inside my html I have this

<p> {{name}}</p>

When I load the page I get _co.name is not defined, but the page still shows the value of name. The component is loading before getting the data I suppose.

What's the best approach to prevent this?

I saw ngIf is not null or something like that, is an option. But then I saw something about Resolve.

Upvotes: 15

Views: 21162

Answers (4)

BeeBee8
BeeBee8

Reputation: 3074

Multiple ways: You can use any one suitable to you.

1. Adding ngIf : If name is undefined or null or '' it will not render the element and prevent errors in console. When name gets defined value it will automatically update the view.

*ngIf="name"

2. Adding async pipe : View will update whenever name gets defined. It waits for name to get defined (or resolved). (name should be a promise or an observable for this to work.)

{{ name | async }}

3. Adding fallback value : This is simply or condition. If name is undefined or null or '' , you can decide which fallback value to assign . {{ name || "" }}

Upvotes: 27

Lucas Hiago
Lucas Hiago

Reputation: 11

You can use {{name?.value}} or {{name?}} inside component.html. Can make treatment to like this in compoment.ts ↓

   ````

    this.route.paramMap.pipe(
      map((param: ParamMap) => {
        // @ts-ignore
        return param.params.id;
      })
    ).subscribe(prodId => {
      this.id = prodId;
      this.productService.getSingleProduct(this.id).subscribe(prod => {
        this.product = prod;
        if (prod.images !== null) {
          this.thumbimages = prod.images.split(';');
        }`enter code here`
      });
    });


  ````

Upvotes: 1

FaTaK
FaTaK

Reputation: 21

As mentioned in previous responses you can use {{ name | async }} but remember if you want to use {{ name | async }}, name must be a promise or an observable.
Otherwise you'll get an error like this :

ERROR Error: InvalidPipeArgument: 'xxx' for pipe 'AsyncPipe'

Upvotes: 2

Abel Valdez
Abel Valdez

Reputation: 2408

Just initialize your variable

name : string = "";

or you can do it inside of the constructor

this.name = "";

Upvotes: 6

Related Questions