javascript - 请求 API 时 View 中看不到任何数据

标签 javascript html angular typescript ionic-framework

我想从 API 检索用户列表。我有几个错误,例如

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Array

Cannot read property 'id' of undefined” when parsing an array declared in a factory

现在我解决了这些错误,但现在的问题是,错误消失了,但我在 View 中看不到任何数据。页面只是空的。我真的不知道我可以进一步尝试什么。奇怪的是,我可以在 get (users) 中记录我的数据,并且还在我的网络选项卡中看到 200 成功,但我无法让它在我的 View 中工作。

这是我的服务:

getList(): Observable<any> {
    return this.http.get<{results: any[]}>(`${this.url}/users`)
    .pipe(
      retry(2),
     // catchError(this.handleError)
    );
  }

页面.ts

 userList: any[] = [];
...
ngOnInit() {
    this.getAllUsers(); // get the users wenn view intializes
}

getAllUsers() {
  // get saved list of users
  this.userService.getList().subscribe(response => {
    console.log(response);
    this.userList = response.results;
  });
  }

页面.html

<ion-list>

          <ion-item lines="none" *ngFor="let user of userList.results">

              <ion-avatar>
                  <ion-img src="assets/friends1.jpeg"> </ion-img>
              </ion-avatar>


                  <h2 class="title">{{user.username}}</h2>

           </ion-item>
</ion-list>

我的回复日志是:

results: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

最佳答案

您已经将结果分配给 userList,因此它已经是一个数组并且不会有 results 属性。将 userList.results 更改为 ngFor 中的 userList

*ngFor="let user of userList"

最好使用异步管道而不是订阅,将您的组件更改为

userList$ = this.userService.getList().pipe(map(response => response.results));

并在模板中使用异步管道

*ngFor="let user of (userList$ | async)"

关于javascript - 请求 API 时 View 中看不到任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58684780/

相关文章:

javascript - 单击按钮 html、css、javascript 时显示更多信息

javascript - 参数和局部变量有什么区别?

javascript - 使用Javascript扫描本地目录,然后使用 "latest"文件更新Anchor标记

javascript - ngx-swiper 将弹出窗口隐藏在其中

javascript - 在主窗口中禁用按钮

javascript - 我如何从其子组件访问主要组件? react js

javascript - 在html中使用 "&times"字改成×

html透明背景

angular - NgSwitch 还是 ComponentFactoryResolver?

angular - 如何使用注入(inject)的对象测试 Angular http 拦截器