Sunday, August 23, 2020

Consuming Observables using async pipe

To consume an Observable using async pipe we need to use the | async syntax in the components view template. In the previous post, we saw how to consume an Observable (response from a http API call) by subscribing to the Observable.

The view template consumes this Observable and displays the response from the http call in the View template. The async pipe automatically subscribes and unsubscribes to the Observable, whenever a new value is emitted from the Observer the async pipe automatically detects the change and refreshes the component.

user.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subscriber } from 'rxjs';
import { User } from './user';
@Injectable({
  providedIn: 'root'
})
export class UserService {
  url = "https://jsonplaceholder.typicode.com/users";
  constructor(private http: HttpClient) { }
  getUsers(): Observable<User[]> {
                                return this.http.get<User[]>(this.url);
                }
}

app.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable, Observer } from 'rxjs';
import { UserService } from '../services/user.service';
import { User } from '../services/user';

@Component({
  selector: 'ajax-pipe',
  templateUrl: './ajax-pipe.html'
})
export class AjaxPipeComponent implements OnInit {
  constructor(private userService: UserService) { }
  users$: Observable<User[]>
  ngOnInit() {
    this.users$ = this.userService.getUsers();
  }
}

app.component.html
<div>
  <ul>
    <li *ngFor="let user of users$ | async" >
      Id: {{user.id}}, Name: {{user.name}}
    </li>
  </ul>
</div>

Output



Search Flipkart Products:
Flipkart.com

No comments: