Angular 5 - Stop errors from undefined object befo

2020-07-09 08:00发布

问题:

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.

回答1:

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.

{{ 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 || "" }}



回答2:

Just initialize your variable

name : string = "";

or you can do it inside of the constructor

this.name = "";