Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 493
kachus22 Avatar asked May 22 '18 17:05

kachus22


People also ask

How can we avoid object is possibly undefined TypeScript?

The "Object is possibly 'undefined'" error occurs when we try to access a property on an object that may have a value of undefined . To solve the error, use the optional chaining operator or a type guard to make sure the reference is not undefined before accessing properties.

How do I tell TypeScript to ignore undefined?

You can add ! (exclamation mark) after a property/variable name. This feature is called “Non-null assertion operator“, basically it means that when you add the exclamation mark after a property/value, you are telling TypeScript that you are certain that value is not null or undefined .

What is undefined error in angular?

This error results from registering a factory which does not return a value (or whose return value is undefined). The following is an example of a factory which will throw this error upon injection: angular.


1 Answers

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

like image 195
BeeBee8 Avatar answered Sep 21 '22 20:09

BeeBee8