typescript Angular 5 - 在加载数据之前停止来自未定义对象的错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50473238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 5 - Stop errors from undefined object before loading data
提问by kachus22
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
在我的 html 里面我有这个
<p> {{name}}</p>
When I load the page I get _co.nameis not defined, but the page still shows the value of name. The component is loading before getting the data I suppose.
当我加载页面时,我得到的页面_co.name未定义,但页面仍显示name. 该组件在获取我想的数据之前正在加载。
What's the best approach to prevent this?
防止这种情况的最佳方法是什么?
I saw ngIfis not nullor something like that, is an option. But then I saw something about Resolve.
我看到ngIf不是null或类似的东西,是一种选择。但后来我看到了一些关于 Resolve 的东西。
回答by Bhushan Babar
Multiple ways: You can use any one suitable to you.
多种方式:您可以使用任何一种适合您的方式。
1. Adding ngIf: If nameis undefinedor nullor ''it will not render the element and prevent errors in console. When namegets defined value it will automatically update the view.
1. 添加 ngIf: If nameis undefinedor nullor''它不会渲染元素并防止控制台出错。当name获得定义的值时,它会自动更新视图。
*ngIf="name"
*ngIf="name"
2. Adding async pipe: View will update whenever namegets defined. It waits for nameto get defined.
2. 添加异步管道:视图将在name定义时更新。它等待name被定义。
{{ name | async }}
{{ name | async }}
3. Adding fallback value: This is simply orcondition. If nameis undefinedor nullor '', you can decide which fallback value to assign .
{{ name || "" }}
3. 添加回退值:这只是or条件。如果name是undefined或null或者'',你可以决定哪些回退值来分配。
{{ name || "" }}
回答by Abel Valdez
Just initialize your variable
只需初始化您的变量
name : string = "";
or you can do it inside of the constructor
或者你可以在构造函数里面做
this.name = "";

