Friday, November 9, 2018

Observables in Angular

We saw that are a way of implementing asynchronous streaming operations, where an observable observables can emit multiple values to its subscribers. 

Angular used observables internally for various features like EventEmitters, Http service to implement Ajax calls, and in the routing module to handle route requests.

Angular provides an EventEmitter class that is used when publishing values from a component through the @Output() decorator. EventEmitter extends Observable, adding an emit() method so it can send arbitrary values.

Angular’s HttpClient returns observables from HTTP method calls. Previously we were using promises to implement ajax calls, Angular uses Observables by default.

Router.events provides events as observables. You can use the filter() operator from RxJS to look for events of interest, and subscribe to them in order to make decisions based on the sequence of events in the navigation process.

Below is a sample code implementation of using observables in Angular services to make Ajax calls, and the component code to subscribe and use the data from the observable.

Service code which returns an observable for Ajax call, not that we don’t use the observables keyword here since Angular’s Http internally uses observables.

export class UserdataService {
  constructor(private http: HttpClient) { }
    getUsersObservable() {
      return this.http.get('https://jsonplaceholder.typicode.com/users')
    }
}

Next we call the service method and subscribe to the observable to receive the response data in the Component.

export class AppComponent {
  userListObservable;
  errorMessage: string;
  constructor(private svcData: UserdataService) { }

  ngOnInit() {
    this.getDataObservable();
  }
 
  getDataObservable() {
    this.svcData.getUsersObservable().subscribe(
      data => this.userListObservable = data,
      err => this.errorMessage = err.status + ' - ' + err.statusText
    );
  }
}


Search Flipkart Products:
Flipkart.com

No comments: