【发布时间】:2018-04-14 03:05:42
【问题描述】:
我不知道我的代码有什么问题。
控制台日志没问题,但是页面有错误Cannot read property 'aqua' of undefined。
home.ts
export class Home implements {
color: any;
constructor(public http: HttpClient) {
this.http.get('https://raw.githubusercontent.com/bahamas10/css-color-names/master/css-color-names.json')
.subscribe(
data => {
this.color = data;
console.log(this.color.aqua); //this logs fine
});
}
}
home.html
{{color.aqua}} <!-- this produce error -->
【问题讨论】:
-
{{ color?.aqua }} -
color变量是在视图首次显示后异步定义的。您应该使用{{color?.aqua}}来防止错误。 -
请向我们展示您的 JSON,因为您的属性颜色看起来未定义。
-
@ConnorsFan 请将您的评论升级为答案,以便我接受它作为答案。我指的教程没有提到猫王运算符:(
-
Jason White 发布了一个您可以接受的答案。 :-)