Skip to main content

Angular - Observables in Angular

Observables in Angular

Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example:
  • The EventEmitter class extends Observable.
  • The HTTP module uses observables to handle AJAX requests and responses.
  • The Router and Forms modules use observables to listen for and respond to user-input events.

Event emitter

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. When you call emit(), it passes the emitted value to the next() method of any subscribed observer.
A good example of usage can be found on the EventEmitter documentation. Here is the example component that listens for open and close events:
Here is the component definition:
EventEmitter
  1. @Component({
  2. selector: 'zippy',
  3. template: `
  4. Toggle
  • `})
  •  
  • export class ZippyComponent {
  • visible = true;
  • @Output() open = new EventEmitter();
  • @Output() close = new EventEmitter();
  •  
  • toggle() {
  • this.visible = !this.visible;
  • if (this.visible) {
  • this.open.emit(null);
  • } else {
  • this.close.emit(null);
  • }
  • }
  • }

  • HTTP

    Angular’s HttpClient returns observables from HTTP method calls. For instance, http.get(‘/api’) returns an observable. This provides several advantages over promise-based HTTP APIs:
    • Observables do not mutate the server response (as can occur through chained .then() calls on promises). Instead, you can use a series of operators to transform values as needed.
    • HTTP requests are cancellable through the unsubscribe() method.
    • Requests can be configured to get progress event updates.
    • Failed requests can be retried easily.

    Async pipe

    The AsyncPipe subscribes to an observable or promise and returns the latest value it has emitted. When a new value is emitted, the pipe marks the component to be checked for changes.
    The following example binds the time observable to the component's view. The observable continuously updates the view with the current time.
    Using async pipe
    @Component({
      selector: 'async-observable-pipe',
      template: `
    observable|async:
    Time: {{ time | async }}
    ` }) export class AsyncObservablePipeComponent { time = new Observable(observer => setInterval(() => observer.next(new Date().toString()), 1000) ); }

    Router

    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. Here's an example:
    Router events
    1. import { Router, NavigationStart } from '@angular/router';
    2. import { filter } from 'rxjs/operators';
    3.  
    4. @Component({
    5. selector: 'app-routable',
    6. templateUrl: './routable.component.html',
    7. styleUrls: ['./routable.component.css']
    8. })
    9. export class Routable1Component implements OnInit {
    10.  
    11. navStart: Observable<NavigationStart>;
    12.  
    13. constructor(private router: Router) {
    14. // Create a new Observable the publishes only the NavigationStart event
    15. this.navStart = router.events.pipe(
    16. filter(evt => evt instanceof NavigationStart)
    17. ) as Observable<NavigationStart>;
    18. }
    19.  
    20. ngOnInit() {
    21. this.navStart.subscribe(evt => console.log('Navigation Started!'));
    22. }
    23. }

    The ActivatedRoute is an injected router service that makes use of observables to get information about a route path and parameters. For example, ActivateRoute.url contains an observable that reports the route path or paths. Here's an example:
    ActivatedRoute
    1. import { ActivatedRoute } from '@angular/router';
    2.  
    3. @Component({
    4. selector: 'app-routable',
    5. templateUrl: './routable.component.html',
    6. styleUrls: ['./routable.component.css']
    7. })
    8. export class Routable2Component implements OnInit {
    9. constructor(private activatedRoute: ActivatedRoute) {}
    10.  
    11. ngOnInit() {
    12. this.activatedRoute.url
    13. .subscribe(url => console.log('The URL changed to: ' + url));
    14. }
    15. }

    Reactive forms

    Reactive forms have properties that use observables to monitor form control values. The FormControlproperties valueChanges and statusChanges contain observables that raise change events. Subscribing to an observable form-control property is a way of triggering application logic within the component class. For example:
    Reactive forms

    1. import { FormGroup } from '@angular/forms';
    2.  
    3. @Component({
    4. selector: 'my-component',
    5. template: 'MyComponent Template'
    6. })
    7. export class MyComponent implements OnInit {
    8. nameChangeLog: string[] = [];
    9. heroForm: FormGroup;
    10.  
    11. ngOnInit() {
    12. this.logNameChange();
    13. }
    14. logNameChange() {
    15. const nameControl = this.heroForm.get('name');
    16. nameControl.valueChanges.forEach(
    17. (value: string) => this.nameChangeLog.push(value)
    18. );
    19. }
    20. }

    Comments