{ "id": "guide/observables-in-angular", "title": "Observables in Angular", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Observables in Angularlink

\n

Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example:

\n\n

Transmitting data between componentslink

\n

Angular provides an EventEmitter class that is used when publishing values from a component through the @Output() decorator.\nEventEmitter extends RxJS Subject, adding an emit() method so it can send arbitrary values.\nWhen you call emit(), it passes the emitted value to the next() method of any subscribed observer.

\n

A good example of usage can be found in the EventEmitter documentation. Here is the example component that listens for open and close events:

\n

<app-zippy (open)=\"onOpen($event)\" (close)=\"onClose($event)\"></app-zippy>

\n

Here is the component definition:

\n\n\n@Component({\n selector: 'app-zippy',\n template: `\n <div class=\"zippy\">\n <div (click)=\"toggle()\">Toggle</div>\n <div [hidden]=\"!visible\">\n <ng-content></ng-content>\n </div>\n </div>\n `,\n})\nexport class ZippyComponent {\n visible = true;\n @Output() open = new EventEmitter<any>();\n @Output() close = new EventEmitter<any>();\n\n toggle() {\n this.visible = !this.visible;\n if (this.visible) {\n this.open.emit(null);\n } else {\n this.close.emit(null);\n }\n }\n}\n\n\n\n

HTTPlink

\n

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:

\n\n

Async pipelink

\n

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.

\n

The following example binds the time observable to the component's view. The observable continuously updates the view with the current time.

\n\n\n@Component({\n selector: 'async-observable-pipe',\n template: `<div><code>observable|async</code>:\n Time: {{ time | async }}</div>`\n})\nexport class AsyncObservablePipeComponent {\n time = new Observable<string>(observer => {\n setInterval(() => observer.next(new Date().toString()), 1000);\n });\n}\n\n\n\n

Routerlink

\n

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:

\n\n\nimport { Router, NavigationStart } from '@angular/router';\nimport { filter } from 'rxjs/operators';\n\n@Component({\n selector: 'app-routable',\n templateUrl: './routable.component.html',\n styleUrls: ['./routable.component.css']\n})\nexport class Routable1Component implements OnInit {\n\n navStart: Observable<NavigationStart>;\n\n constructor(private router: Router) {\n // Create a new Observable that publishes only the NavigationStart event\n this.navStart = router.events.pipe(\n filter(evt => evt instanceof NavigationStart)\n ) as Observable<NavigationStart>;\n }\n\n ngOnInit() {\n this.navStart.subscribe(evt => console.log('Navigation Started!'));\n }\n}\n\n\n\n

The ActivatedRoute is an injected router service that makes use of observables to get information about a route path and parameters. For example, ActivatedRoute.url contains an observable that reports the route path or paths. Here's an example:

\n\n\nimport { ActivatedRoute } from '@angular/router';\n\n@Component({\n selector: 'app-routable',\n templateUrl: './routable.component.html',\n styleUrls: ['./routable.component.css']\n})\nexport class Routable2Component implements OnInit {\n constructor(private activatedRoute: ActivatedRoute) {}\n\n ngOnInit() {\n this.activatedRoute.url\n .subscribe(url => console.log('The URL changed to: ' + url));\n }\n}\n\n\n\n

Reactive formslink

\n

Reactive forms have properties that use observables to monitor form control values. The FormControl properties 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:

\n\n\nimport { FormGroup } from '@angular/forms';\n\n@Component({\n selector: 'my-component',\n template: 'MyComponent Template'\n})\nexport class MyComponent implements OnInit {\n nameChangeLog: string[] = [];\n heroForm: FormGroup;\n\n ngOnInit() {\n this.logNameChange();\n }\n logNameChange() {\n const nameControl = this.heroForm.get('name');\n nameControl.valueChanges.forEach(\n (value: string) => this.nameChangeLog.push(value)\n );\n }\n}\n\n\n\n\n \n
\n\n\n" }