角度2 HTTP请求json数据不显示不使用| JSON
Json数据不显示。我正在做一个httpGet,一切似乎都很好。看来数据被加载到我的数组中,并且有3个对象。然而,没有任何内容显示在HTML,{{associateList}}中,或者当我执行“console.log”时。我必须把它管到JSON {{associateList | JSON}}然后我得到了所有东西,当然这一切都在一个大块。 我似乎无法访问数组中的单个对象,我似乎无法弄清楚该怎么做。角度2 HTTP请求json数据不显示不使用| JSON
这是我获得服务:
getAssociatesData(){
return this.http.get('http://Api/Associates').map(res =>res.json());
这是我如何订阅和其他的东西:
associateList: associateData[];
this.GetDataServices.getAssociatesData().subscribe(
associates =>{this.associateList= (associates)},
error => this.serviceError=error,
() => {
this.formatAssociates();
console.log('associates loaded');
//this.isLoading.next(false)
}
);
formatAssociates(){
let associateCount = this.associateList.length;
console.log('number of associates: ' + associateCount);
this.showAssociates = true;
}
interface associateData{
id : number;
firstName : string;
lastName : string;
middleName : string;
fullName : string;
}
而在HTML:
<div *ngIf="showAssociates">
<span *ngFor="let associate of associateList; let count=index">
<div id={{count}} >
associate# = {{count}}
associateID = {{(associate | async).id}}
First Name = {{associate.firstName}}
Last Name = {{associate.lastName}}
Middle Name = {{associate.middleName}}
Full Name = {{associate.fullName}}
</div>
</span>
</div>
{{associateList | json}}
的问题是,我当我将“associateList”传递给json时,只能看到数据。我无法显示个别元素。
据我所见,你有一个名为formatAssociates()
的方法this.showAssociates = true;
,这个方法在错误的情况下被触发,所以在设置this.associateList
之后,你会看到这些值。
你没有看到它们导致变量可能是undefined或false,所以为了快速尝试,删除if条件来证明我的理论。
希望它有帮助。
这不是。它输出的字段名称:关联#= associateID = .... –
以及你应该给你更多的信息,你面临着什么,这并没有太多你的意见。 json格式,plunkr ... –
您的控制台是否显示任何错误?最近我有类似的问题,这是由于HTML渲染比异步调用更快。检查此链接
Unable to display object array of an object in Angular 2 template
我使用“showAssociates”在数组中有东西后控制HTML的呈现。 Console.log也不会给我数据。我想知道我正在阅读的HTTP数据是否在标题中缺少某些内容,但当我通过将其管理到JSON来查看它时,它看起来很好。 –
控制台没有错误。 –
@GabrielO如果您将模板中的所有数据传递给json,那么您只需要担心的是如何使用ngFor和ngIf。代码看起来不错。你能模拟你的代码吗?所以我们很容易玩你的代码。 – amulamul
你的问题是,你需要你的角度分量的init
生命周期内执行该服务。
import {Component, OnInit} from '@angular/core';
//components stuff goes here
export class AssociateComponent implements OnInit {
associateList: associateData[];
constructor(getAssociateDataService: getAssociateDataService) {}
ngOnInit(){
this.GetDataServices.getAssociatesData().subscribe(
associates =>{this.associateList= (associates)},
error => this.serviceError=error,
() => {
this.formatAssociates();
console.log('associates loaded');
//this.isLoading.next(false)
}
);
}
formatAssociates(){
let associateCount = this.associateList.length;
console.log('number of associates: ' + associateCount);
this.showAssociates = true;
}
interface associateData{
id : number;
firstName : string;
lastName : string;
middleName : string;
fullName : string;
}
}
它在ngOnInit中。没有什么不同。数据被加载到associateList数组中,并检查显示对象的确切数量的长度。我似乎无法访问单个对象,只能看到管道到JSON时的所有内容。 –
你的JSON是怎样的?你可以发布吗? :) – Alex