Angular 5-在加载数据之前停止来自未定义对象的错误 [英] 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?
假设我有这个
name : string;
constructor(private data: DataService) {
this.data.name.subscribe(res => this.name = res);
}
在我的html中,我有这个
Inside my html I have this
<p> {{name}}</p>
加载页面时,未定义_co.name
,但是页面仍显示name
的值.在获取我想得到的数据之前,正在加载组件.
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?
我看到ngIf
不是null
或类似的东西,是一个选择.但是后来我看到了一些有关Resolve的信息.
I saw ngIf
is not null
or something like that, is an option. But then I saw something about Resolve.
推荐答案
多种方式:您可以使用任何一种适合您的方式.
Multiple ways: You can use any one suitable to you.
1.添加ngIf :如果name
是undefined
或null
或''
,它将不会呈现该元素并防止控制台错误.当name
获得定义值时,它将自动更新视图.
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.添加异步管道:只要定义了name
,视图就会更新.它等待name
被定义.
2. Adding async pipe : View will update whenever name
gets defined. It waits for name
to get defined.
{{ name | async }}
3.添加后备值:这只是or
条件.如果name
是undefined
或null
或''
,则可以决定要分配的后备值.
{{ name || "" }}
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 || "" }}
这篇关于Angular 5-在加载数据之前停止来自未定义对象的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!