Angular 2 获取json 数据并将其定义为组件中的新数组
Angular 2 get json data and define it as new array in component
我得到了我的 json 文件,我正在通过服务获取它。然后我试图在组件中订阅它,但在 console.log(this.jsonObj)
中我得到空数组。另外,如果我写 console.log(data)
- 我会得到 json 数据。
服务:
objUrl = 'assets/jsons/obs.json';
constructor(private http: HttpClient) {
console.log('Hello ObjectsProvider Provider');
}
getObjectsJson() {
return this.http.get(this.objUrl);
}
组件:
jsonObj = {};
this.object.getObjectsJson().subscribe((data =>
this.jsonObj = data
))
console.log(this.jsonObj)
服务方法是异步的,因此当 http 调用 returns 时,subscribe() 中的代码(进行分配)会在未来某个时间执行。您的日志语句在订阅之外,因此它发生在分配之前。尝试在分配后立即将日志语句放入订阅中。
Issue
您正在尝试以 Synchronous
方式获取 Asynchronous
数据。您正在 Observable 之外记录数据 console.log(this.jsonObj)
。因此它会在不等待结果来自 API.
的情况下执行
Fix
只需将日志或任何要在 API 之后执行的代码移到 subscribe
中。所以你的代码看起来像
jsonObj = [];
this.object.getObjectsJson().subscribe((data =>
this.jsonObj = data;
console.log(this.jsonObj); //<-- data will be appear here.
))
console.log(this.jsonObj) 会在服务器响应之前运行。您可以按原样使用它。它将 运行 完美。你可以这样测试
<p *ngIf="jsonObj !== undefined">{{jsonObj.field}}</p>
如果你想用console.log查看它,只需像这样在订阅中添加它
this.http.getObjectsJson().subscribe((data => {
this.jsonObj = data
console.log(this.jsonObj)
}));"
我得到了我的 json 文件,我正在通过服务获取它。然后我试图在组件中订阅它,但在 console.log(this.jsonObj)
中我得到空数组。另外,如果我写 console.log(data)
- 我会得到 json 数据。
服务:
objUrl = 'assets/jsons/obs.json';
constructor(private http: HttpClient) {
console.log('Hello ObjectsProvider Provider');
}
getObjectsJson() {
return this.http.get(this.objUrl);
}
组件:
jsonObj = {};
this.object.getObjectsJson().subscribe((data =>
this.jsonObj = data
))
console.log(this.jsonObj)
服务方法是异步的,因此当 http 调用 returns 时,subscribe() 中的代码(进行分配)会在未来某个时间执行。您的日志语句在订阅之外,因此它发生在分配之前。尝试在分配后立即将日志语句放入订阅中。
Issue
您正在尝试以 Synchronous
方式获取 Asynchronous
数据。您正在 Observable 之外记录数据 console.log(this.jsonObj)
。因此它会在不等待结果来自 API.
Fix
只需将日志或任何要在 API 之后执行的代码移到 subscribe
中。所以你的代码看起来像
jsonObj = [];
this.object.getObjectsJson().subscribe((data =>
this.jsonObj = data;
console.log(this.jsonObj); //<-- data will be appear here.
))
console.log(this.jsonObj) 会在服务器响应之前运行。您可以按原样使用它。它将 运行 完美。你可以这样测试
<p *ngIf="jsonObj !== undefined">{{jsonObj.field}}</p>
如果你想用console.log查看它,只需像这样在订阅中添加它
this.http.getObjectsJson().subscribe((data => {
this.jsonObj = data
console.log(this.jsonObj)
}));"