0

I have the following code:

HTML

<div *ngIf="users">
    <ul>
        <li *ngFor="let user of users">{{ user.name }}</li>
    </ul>
</div>

TS FILE

export class AppComponent implements OnInit {
  constructor(private http: HttpClient) {};
  users: any;
  ngOnInit() {
   this.subscription = this.http.get('https://jsonplaceholder.typicode.com/users').subscribe(users => {
    this.users = users;
   })
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

i want to avoid manually unsubscribing and want to use async. How can i convert this to work with async pipe because when i try

<li *ngFor="let user of users | async">{{ user.name }}</li>

i get

Error: InvalidPipeArgument: '[object Object],[object Object],[object Object],
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

2 Answers2

2

The angular async pipe allows the subscription to observables inside of the angular template syntax. It also takes care of unsubscribing from observables automatically. So you Shouldn't subscribe that. TS FILE

ngOnInit() {
   this.users = this.http.get('https://jsonplaceholder.typicode.com/users');
}

HTML

<li *ngFor="let user of users | async">{{ user.name }}</li>
Arash Hatami
  • 522
  • 4
  • 10
0

You can use async pipe if you have an observable. Since you subscribed to it, the restul is no longer an observable.

So try something like this:

export class AppComponent implements OnInit {
    constructor(private http: HttpClient) {};
    users: any;
    ngOnInit() {
        this.users = this.http.get('https://jsonplaceholder.typicode.com/users');
    }
}
Lung Radu
  • 15
  • 3