Async pipe in Angular does not work with my custom observables

I've been trying to implement the async pipe in my template, but I'm encountering difficulties retrieving data from my API. To store and retrieve the data, I have utilized a behavior subject to create an observable. However, when I attempt to display the data on the HTML page, I encounter the following 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>

https://i.sstatic.net/PZpMF.png

I'm really eager to understand why this isn't working, so if anyone has any insights, please share. Thank you.

Answer №1

In case you find yourself in need of utilizing a BehaviorSubject within an asynchronous workflow, here is a helpful resource: https://angular.io/api/common/AsyncPipe

Here's how you can implement this in your component:

friend$: Observable<[]> = [];

getFriendList(userId: string) {
  this.friend$ = this.mainService.getLastFriend(+userId).pipe(
    catchError(error => of(error))
  );
}

Implementation in 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)
  );
} 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The ElementRef was modified following the activation of a click event

Let me explain my current situation: I am working with 3 components: MainComponent, ComponentA, and ComponentB. MainComponent dynamically loads ComponentA. ComponentA contains a button that, when clicked, calls MainComponent.addComponent(ComponentB). exp ...

Angular displays an error message and applies an invalid class when a form is submitted

I have created a form in Angular(5) using a template-driven approach. My goal is to display error messages and apply different styles to the input fields when they are invalid, especially when the form is submitted. Currently, I am able to achieve this fu ...

The expected property 'label' is not found in the object type '{ handleClick: () => void; }', but it is required in the object type '{ handleClick: () => void; label: string; }'

I'm encountering difficulties when describing the types of my props. The issue arises with the following code: <PostButton handleClick={props.upvote}/> <PostButton2 handleClick={props.downvote}/> An error message is displayed: Pro ...

Using ngIf with Promises causes a malfunction

I have extensively tested this issue and I am unable to understand why the code below is not functioning as expected. The problem arises when the @Input variable is received and the user object is fetched from the service, the ngIf directive in the templat ...

Error in MEAN Stack: Unable to access the property 'companyTitle' because it is undefined

I have established a MongoDB collection named joblist in my database. Additionally, I have developed a DB schema known as jobList.js. var mongoose = require('mongoose'); const joblistSchema = mongoose.Schema({ companyTitle: String, jobT ...

Unable to correlate the response with the designated object

I'm currently facing an issue while attempting to utilize Angular4 HttpClient with an observable object that I've defined. My challenge lies in mapping the response to the designated object. The root of the problem appears to be related to my us ...

Can I include `ChangeDetectorRef` in an Angular 4 service constructor?

In my service file, I have a system that alerts about Subjects. The value is set and then reset to null after 3 seconds using the setTimeout() method. However, upon adding changeDetection: ChangeDetectionStrategy.OnPush to the app.component.ts, it appears ...

Tips for resolving conflicts between sequelize and angular within a lerna monorepo using typescript

Managing a monorepo with Lerna can be quite challenging, especially when working with both Node.js and Angular in the same project. In my setup, Angular is using "typescript": "~3.5.3". For Node.js to work seamlessly with Sequelize, I have the following ...

Enhance the navigation scroll bar with a blur effect

I'm looking to create a navigation bar with a cool blur effect as you scroll. Everything seems to be working fine, except when I refresh the page the scrollbar position remains the same and window.pageYOffset doesn't give me the desired result. T ...

What is the best method for arranging components?

I have a Product component that contains crucial information about various products. Adjacent to this data, there is a separate component called Buttons, which includes two buttons - one for adding the product to a favorites list and another for adding it ...

Encountering the following error message: "E11000 duplicate key error collection"

Currently, I am in the process of developing an ecommerce platform using the MERN stack combined with TypeScript. As part of this project, I am working on a feature that allows users to provide reviews for products. The goal is to limit each user to only o ...

Converting JSON objects into TypeScript classes: A step-by-step guide

My challenge lies in converting Django responses into Angular's User array. This conversion is necessary due to variations in variable names (first_name vs firstName) and implementing specific logic within the Angular User constructor. In simple term ...

Maintaining the consistent structure of build directories within a Docker container is crucial, especially when compiling TypeScript code that excludes the test

Our application is built using TypeScript and the source code resides in the /src directory. We have tests located in the /tests directory. When we compile the code locally using TSC, the compiled files are deposited into /dist/src and /dist/test respectiv ...

Encountering an issue with Angular virtual scrolling: ViewDestroyedError arises when trying to utilize a destroyed view during detectChanges operation

My implementation involves using virtual scrolling from the cdk within a trigger-opening sidenav on a mat-radio element. Here is the code snippet: ts - ... @Component({ selector: 'app-generic-options-list', templateUrl: './generic-opt ...

"Error encountered: Route class unable to reach local function in TypeScript Express application" #codingissues

Experiencing an 'undefined' error for the 'loglogMePleasePlease' function in the code snippet below. Requesting assistance to resolve this issue. TypeError: Cannot read property 'logMePleasePlease' of undefined This error ...

Replicating an array of typed objects in Angular2

I have a collection of specific object types and I'm looking to duplicate it so that I can work on a separate version. In order for the configuratorProduct to function correctly, I need to provide it with a copy of the listProducts values: listPro ...

Unable to display complete content of Ionic 3 webpage

Trying to print a specific part of an Ionic page which contains a long list of items. However, encountering an issue where the entire list doesn't fit on one page and requires scrolling down to view all items. Expecting the print dialog, triggered by ...

Following the upgrade to Angular 6, the [WDS] connection disconnects on Internet Explorer after the page has

After upgrading my Angular Project from version 5 to 6, I encountered issues specifically with Internet Explorer 11. Whenever I attempt to load the live dev server on localhost:4200, the login page displays but then immediately disconnects from the live de ...

Building secure and responsive routes using next.js middleware

After setting up my routes.ts file to store protected routes, I encountered an issue with dynamic URLs not being properly secured. Even though regular routes like '/profile' were restricted for unauthenticated users, the dynamic routes remained a ...

Acquire Superheroes in Journey of Champions from a REST endpoint using Angular 2

Upon completing the Angular 2 Tour of heroes tutorial, I found myself pondering how to "retrieve the heroes" using a REST API. If my API is hosted at http://localhost:7000/heroes and returns a JSON list of "mock-heroes", what steps must I take to ensure a ...