我试图显示从服务中检索到的数据,并将其显示在我的HTML中。我的方法可以工作,但是它在控制台中输出错误,我不知道如何解决这些错误。
下面是我的应用程序的工作方式:
app.component.ts
// initialize the variable that will store the returned message object
messages: any;
// call the service
this.TaskService.getMessages()
.subscribe(response => {
// response will be an object with two key:value pairs inside
this.messages = response;
});
以及我如何在html中显示它。
<div>
<span class="hello">{{messages.hello}}</span>
<span class="goodbye">{{messages.goodbye}}</span>
</div>
每当运行此操作时,将正确显示html值,但在控制台中会收到以下错误:
错误TypeError:无法读取未定义的属性“hello” 错误TypeError:无法读取未定义属性的“再见”
我之所以会出现这种情况,是因为当模板试图加载值时,服务还没有检索完它们。但是,我不知道如何解决这个问题,如果是这样的话。
(除了创建初始化“hello”和“再见”的组件级变量之外,在服务调用完成时更改它们的值,但这似乎效率低下)
如何在不出现控制台错误的情况下显示从服务中检索的值,并在HTML中显示它们?
谢谢你的帮助。
发布于 2018-01-01 18:56:12
出现此错误是因为在呈现模板时,由于异步分配了messages
值,因此仍未定义它。有几种方法可以解决这个问题:
1. Elvis算子
Angular支持在绑定html模板时使用埃尔维斯算子。
<div>
<span class="hello">{{messages?.hello}}</span>
<span class="goodbye">{{messages?.goodbye}}</span>
</div>
请注意,您只能在html模板中使用elvis运算符,而不能在类型记录或JavaScript中使用,因为它们还不受支持。
2.使用*ngIf
要防止模板与任何未定义的对象进行绑定,只需删除DOM,这正是*ngIf
所做的:
<div *ngIf="messages !== undefined">
<span class="hello">{{messages.hello}}</span>
<span class="goodbye">{{messages.goodbye}}</span>
</div>
或者简单地说,如果你相信对象的真实性:
<div *ngIf="messages">
<span class="hello">{{messages.hello}}</span>
<span class="goodbye">{{messages.goodbye}}</span>
</div>
发布于 2018-01-01 18:54:06
您可以使用安全航行操作员 ?.
来防止messages
为null的情况:
<div>
<span class="hello">{{messages?.hello}}</span>
<span class="goodbye">{{messages?.goodbye}}</span>
</div>
https://stackoverflow.com/questions/48054944
复制