I want to use async pipe in my template , but I have a problem getting data from my api. I have used behavior subject to next the data and then keep it in an observable. When I call the observable in html I get this error:
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to
Iterables such as Arrays
friendList.ts
public friendSubject = new BehaviorSubject<any>(null);
public friend$: Observable<any> = this.friendSubject.asObservable();
getFriendList(userID: string) {
userID = this.userID;
try {
return this.mainService.getFriendList(userID).subscribe((friendList) => {
console.log(friendList)
this.friendSubject.next(friendList);
// friendList.data.forEach((friend => {
// }))
console.log(this.friendSubject)
})
}
catch (err) {
}
}
friendList.html
<ion-label class="friend-count" *ngIf="friend$ | async">{{(friend$ | async)?.length}}</ion-label>
//this works..
<div class="friend-list">
<div *ngFor="let i = index; let friend of friend$ | async" class="friend">
<div class="custom-img">
<ion-img class="friend-img" [src]="friend?.frendsView.photo"></ion-img>
</div>
<ion-label></ion-label>
</div>
</div>
I really want to understand why it doesn't work pls
This will help you if you need to use a BehaviorSubject with an asynchronous pipeline. https://angular.io/api/common/AsyncPipe
Your component:
friend$: Observable<[]> = [];
getFriendList(userId: string) {
this.friend$ = this.mainService.getLastFriend(+userId).pipe(
catchError(error => of(error))
);
}
your mainService:
private friendSubject = new BehaviorSubject<[]>(null);
private users = [
{
userId: 1,
name: 'Max',
friendList: {
{id: 1, name: 'Bob'},
{id: 2, name: 'Alex'},
{id: 3, name: 'Kate'}
}
}
];
getLastFriend(userId: number): Observable<[]> {
const friendList = this.getFriendList(userId);
this.friendSubject.next(friendList);
return this.friendSubject.asObservable();
}
private getFriendList(userId: number): [] {
return of(users).pipe(
filter( ({userId}) => userId === userId),
map(user => user.friendList)
);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments