ngFor JSON 对象数组异步等待角度 13 未绑定

发布于 2025-01-13 14:45:14 字数 2159 浏览 1 评论 0原文

这是我的打字稿页面。

export class ListUsersComponent implements OnInit {
  users: any;
  constructor(){}

  async ngOnInit() {
    await this.loadUser();
  }

  async loadUser() {
      const us = this.userService.getUsers().pipe(
       first(),
      catchError((errorMessage) => {
        return of(EMPTY_UserProfile);
      })
).subscribe((data: any) => {
  this.users = data;
  console.log(this.users);
});
this.subscriptions.push(us);
  }
}

由于 this.user 很容易绑定,它给我的结果是

[
  {
    "id": 1,
    "userName": "xyz",
  },
  {
    "id": 2,
    "userName": "xyz2",
  }
]

Here is the HTML ngFor

<tr align="center" *ngFor="let user of users | async; let i=index">
     <td>{{user.id}}</td>
     <td>{{user.userName}} </td>
</tr>

当我尝试通过文章找到的所有可能的方法时,没有显示任何输出。当我尝试在构造函数中调用固定的Array JSON对象但在async await中调用时,它会起作用>ngOnInit 并没有真正帮助我。 我可能错过了什么?

更新 1:

这是调用服务的可观察部分。

    getUsers(id?: string): Observable<UserDetails> {
    const auth = this.getAuthFromLocalStorage();
    if (!auth || !auth.authToken) {
      return of(undefined);
    }

    this.isLoadingSubject.next(true);
    return this.userHttpService.getUsers(auth.authToken, '').pipe(
      map((user: UserDetails) => {
        if (user) {
          this.currentUsers = new BehaviorSubject<UserDetails>(user);
        } else {
          this.logout();
        }
        return user;
      }),
      finalize(() => this.isLoadingSubject.next(false))
    );
  }

更新2: 这从更新 1 中调用为 this.userHttpService.getUsers(auth.authToken, '')

getUsers(token, Id?: string): Observable<UserDetails> {
    const httpHeaders = new HttpHeaders({
      Authorization: `Bearer ${token}`,
    });
    return this.http.get<UserDetails>(`${API_URL}/GetCompanyUsers?Id=` + Id + `&pageNumber=1` + `&pageSize=1`, {
      headers: httpHeaders,
    });
  }

Here is my typescript page.

export class ListUsersComponent implements OnInit {
  users: any;
  constructor(){}

  async ngOnInit() {
    await this.loadUser();
  }

  async loadUser() {
      const us = this.userService.getUsers().pipe(
       first(),
      catchError((errorMessage) => {
        return of(EMPTY_UserProfile);
      })
).subscribe((data: any) => {
  this.users = data;
  console.log(this.users);
});
this.subscriptions.push(us);
  }
}

As the this.user bind easily, it gives me result as

[
  {
    "id": 1,
    "userName": "xyz",
  },
  {
    "id": 2,
    "userName": "xyz2",
  }
]

Here is the HTML ngFor.

<tr align="center" *ngFor="let user of users | async; let i=index">
     <td>{{user.id}}</td>
     <td>{{user.userName}} </td>
</tr>

There is no output shown as I tried every possible way I found through articles. It works when I try to call a fixed Array JSON object in the constructor but calling async await in ngOnInit doesn't really help me.
I might be missing something?

Update 1:

Here is the observable part where service is being called.

    getUsers(id?: string): Observable<UserDetails> {
    const auth = this.getAuthFromLocalStorage();
    if (!auth || !auth.authToken) {
      return of(undefined);
    }

    this.isLoadingSubject.next(true);
    return this.userHttpService.getUsers(auth.authToken, '').pipe(
      map((user: UserDetails) => {
        if (user) {
          this.currentUsers = new BehaviorSubject<UserDetails>(user);
        } else {
          this.logout();
        }
        return user;
      }),
      finalize(() => this.isLoadingSubject.next(false))
    );
  }

Update 2:
this calls from Update 1 as this.userHttpService.getUsers(auth.authToken, '')

getUsers(token, Id?: string): Observable<UserDetails> {
    const httpHeaders = new HttpHeaders({
      Authorization: `Bearer ${token}`,
    });
    return this.http.get<UserDetails>(`${API_URL}/GetCompanyUsers?Id=` + Id + `&pageNumber=1` + `&pageSize=1`, {
      headers: httpHeaders,
    });
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时间海 2025-01-20 14:45:14

这里有几件事。

  1. 无需在此处添加 async wait,正如 GRD 在评论中所说的那样。
  2. 您已经订阅,因此无需使用异步管道。

注意:如果您直接使用 observable,则使用异步管道。

  users: any[] = [];
  constructor(){}

  ngOnInit() {
    this.loadUser();
  }

  loadUser() {
      const sb = this.userService.getUsers().pipe(
       first(),
       catchError((errorMessage) => {
        return of(EMPTY_UserProfile);
       })
      ).subscribe((users: UserProfile[]) => {
      this.users = users; //data is recieved but not shown on ngFor HTML page
    });
    this.subscriptions.push(sb);
  }
}
<tr align="center" *ngFor="let user of users; let i=index">
     <td>{{user.id}}</td>
     <td>{{user.userName}} </td>
</tr>

A couple of things here.

  1. No need to add async await here as GRD also said in the comment.
  2. you already subscribing so no need to use the async pipe.

Note: if you are directly using observable then use async pipe.

  users: any[] = [];
  constructor(){}

  ngOnInit() {
    this.loadUser();
  }

  loadUser() {
      const sb = this.userService.getUsers().pipe(
       first(),
       catchError((errorMessage) => {
        return of(EMPTY_UserProfile);
       })
      ).subscribe((users: UserProfile[]) => {
      this.users = users; //data is recieved but not shown on ngFor HTML page
    });
    this.subscriptions.push(sb);
  }
}
<tr align="center" *ngFor="let user of users; let i=index">
     <td>{{user.id}}</td>
     <td>{{user.userName}} </td>
</tr>
茶底世界 2025-01-20 14:45:14

正如 async 管道定义所述

异步管道订阅 Observable 或 Promise 并返回它发出的最新值。

如果您要绑定到可观察对象,则需要应用异步管道,在您的情况下,在您订阅loadUser()方法中到一个可观察的,因此不需要使用异步管道。

如果您想应用 async 管道,请像这样修改 loadUser 方法

  loadUser():Observable<any[]> {
  const sb = this.userService.getUserProfile().pipe(
   first(),
   catchError((errorMessage) => {
    return of(EMPTY_UserProfile);
   })
  );
this.subscriptions.push(sb);
return sb;
 }

,然后您必须像这样修改 *ngFor

<tr align="center" *ngFor="let user of loadUser() | async; let i=index">
 <td>{{user.id}}</td>
 <td>{{user.userName}} </td>
</tr>

As the async pipe definition states

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.

You'll need to apply async pipe, if you are binding to an observable, in your case in the loadUser() method you are subscribing to an observable and hence no need to use async pipe.

If you want to apply async pipe, then modify the loadUser method like this

  loadUser():Observable<any[]> {
  const sb = this.userService.getUserProfile().pipe(
   first(),
   catchError((errorMessage) => {
    return of(EMPTY_UserProfile);
   })
  );
this.subscriptions.push(sb);
return sb;
 }

and then you'll have to modify the *ngFor like this

<tr align="center" *ngFor="let user of loadUser() | async; let i=index">
 <td>{{user.id}}</td>
 <td>{{user.userName}} </td>
</tr>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文