我正在关注 this tutorial .在从 api.github 获取用户列表的过程中出现错误:
Cannot find a differ supporting object '[object Object]'
我认为它与
有关 <ul>
<li *ngFor = "#user of users">
{{user | json}}
</li>
</ul>
在我的代码中,因为在它之前没有任何错误,我不确定数据是否来自 get 请求,只是点击没有给出任何错误,这是我目前的代码
@Component({
selector: 'router',
pipes : [],
template: `
<div>
<form [ngFormModel] = "searchform">
<input type = 'text' [ngFormControl]= 'input1'/>
</form>
<button (click) = "getusers()">Submit</button>
</div>
<div>
<ul>
<li *ngFor = "#user of users">
{{user | json}}
</li>
</ul>
</div>
<router-outlet></router-outlet>
`,
directives: [FORM_DIRECTIVES]
})
export class router {
searchform: ControlGroup;
users: Array<Object>[];
input1: AbstractControl;
constructor(public http: Http, fb: FormBuilder) {
this.searchform = fb.group({
'input1': ['']
})
this.input1 = this.searchform.controls['input1']
}
getusers() {
this.http.get(`https://api.github.com/
search/users?q=${this.input1.value}`)
.map(response => response.json())
.subscribe(
data => this.users = data,
error => console.log(error)
)
}
}
bootstrap(router, [HTTP_PROVIDERS])
最佳答案
我认为您在响应负载中收到的对象不是数组。也许您要迭代的数组包含在一个属性中。您应该检查接收到的数据的结构...
你可以尝试这样的事情:
getusers() {
this.http.get(`https://api.github.com/search/users?q=${this.input1.value}`)
.map(response => response.json().items) // <------
.subscribe(
data => this.users = data,
error => console.log(error)
);
}
编辑
根据 Github 文档 (developer.github.com/v3/search/#search-users),响应格式为:
{
"total_count": 12,
"incomplete_results": false,
"items": [
{
"login": "mojombo",
"id": 1,
(...)
"type": "User",
"score": 105.47857
}
]
}
因此用户列表包含在 items
字段中,您应该使用它:
getusers() {
this.http.get(`https://api.github.com/search/users?q=${this.input1.value}`)
.map(response => response.json().items) // <------
.subscribe(
data => this.users = data,
error => console.log(error)
);
}
关于Angular:找不到不同的支持对象 '[object Object]',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35660306/