我正在尝试一个必须从 JSON 文件中提取数据的简单组件。我几乎从生成的 Fountain 应用程序复制功能,但由于某种原因我无法获得所需的结果。我有一个像这样的组件:
import {Component, Inject} from "@angular/core";
import {Http} from '@angular/http';
@Component({
selector: 'body-selector',
template: require('./body.html')
})
@Inject(Http)
export class BodyComponent {
constructor(http: Http) {
this.http = http;
this.getText('app/texts/main.json').subscribe(result => {
console.log(result);
this.texts = result;
});
console.log(this.texts);
}
getText(url) {
return this.http.get(url).map(response => response.json());
}
}
在第一个 console.log
上,我有 [Object object] [Object object] [Object object]
,这是正确的,因为我在 JSON 中有三个条目。然而,在第二个我有未定义
,这在浏览器中变成了一个错误。
Error in ./BodyComponent class BodyComponent - inline template:3:6 caused by: Cannot read property 'title' of undefined
我正在查看喷泉应用程序生成的示例,但我不明白我做错了什么。
最佳答案
您有多个问题:
第一个
console.log
位于回调内部,其中this.texts
刚刚被设置。然而,第二个在回调之外,所以它不会。因此,您总是会看到undefined
,因为......您从未为
this.texts
设置默认值,并且您的模板显然没有任何例如*ngIf
来处理它为null
或undefined
,从而在调用回调之前导致错误。
下面是您的代码,重构为以空的 this.texts
开头(假设它应该是一个数组;请适应口味)并简化 Http
的注入(inject)。另请注意注释,并且我使用 templateUrl
来避免 require
和 OnInit
在组件生命周期稍后触发 HTTP 调用而不是在构造函数中执行它。
import {Component, OnInit} from '@angular/core'; // note consistent quotes
import {Http} from '@angular/http';
@Component({
selector: 'body-selector',
templateUrl: './body.html',
})
export class BodyComponent implements OnInit {
texts: any[] = []; // start with an empty array
constructor(private http: Http) { } // inject Http here, no need to assign to this
ngOnInit() {
this.http
.get('app/texts/main.json')
.map(response => response.json())
.subscribe(result => {
console.log(result); // only log *inside* the callback
this.texts = result;
});
// outside the callback, the HTTP call hasn't yet finished
}
}
您还可以通过在 HTML 中添加 ngIf
来解决此问题,以防止在数据加载之前加载元素。
<div class="main-container" *ngIf="texts">
...
</div>
我强烈建议您阅读基本的 Angular 2 教程来掌握这些内容,请参阅例如the Tour of Heroes .
关于javascript - 无法将 JSON 结果绑定(bind)到组件变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40639818/