Angular:找不到不同的支持对象 '[object Object]'

标签 angular angular2-routing angular2-directives angular2-http

我正在关注 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/

相关文章:

javascript - Angular 6 - 路由未发生 - Mat-table 行

html - 对于标签集行,我想以 Angular 2 显示按钮

滚动页面时,Angular 9+ 和 ng-bootstrap 工具提示在固定元素上失败,是否有比我更好的修复方法?

javascript - 从数组中删除项目 - Angular 4

angular - Angular 如何确定路由的优先级 - 顶级与子级

angular - 实现自动完成

css - 如何将当前标签实例传递给angular2中的事件

angular - Bootstrap 5 with Angular 12 : bootstrap (navbar, 下拉菜单)在通过 JavaScript 获取/创建 Bootstrap 实例后,交互被阻止

angular - 错误 NG6002 : Appears in the NgModule. 导入 <module>,但无法解析为 NgModule 类

angular - 使用 Resolve 停止路由更改