Angular 5-在加载数据之前停止来自未定义对象的错误 [英] Angular 5 - Stop errors from undefined object before loading data

查看:97
本文介绍了Angular 5-在加载数据之前停止来自未定义对象的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

防止仍未定义的对象在控制台中发生错误的最佳方法是什么?

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 :如果nameundefinednull'',它将不会呈现该元素并防止控制台错误.当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条件.如果nameundefinednull'',则可以决定要分配的后备值. {{ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆