Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example:
Define custom events that send observable output data from a child to a parent component.
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.
1.0 Transmitting data between components
EventEmitter class that is used when publishing values from a component through the @Output() decorator. EventEmitter extends RxJS Subject, 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.
@Component({
selector: 'app-zippy',
template: `
<div class="zippy">
<div (click)="toggle()">Toggle</div>
<div [hidden]="!visible">
<ng-content></ng-content>
</div>
</div>
`,
})
export class ZippyComponent {
visible = true;
@Output() open = new EventEmitter<any>();
@Output() close = new EventEmitter<any>();
toggle() {
this.visible = !this.visible;
if (this.visible) {
this.open.emit(null);
} else {
this.close.emit(null);
}
}
}
2.0 HTTP
Angular’s HttpClient returns observables from HTTP method calls.
POST, PUT, GET, DELETE, etc
3.0 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.
@Component({
selector: 'async-observable-pipe',
template: `<div><code>observable|async</code>:
Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
time = new Observable<string>(observer => {
setInterval(() => observer.next(new Date().toString()), 1000);
});
}
4.0 Router
Router.events provides events as observables.
import { Router, NavigationStart } from '@angular/router';
import { filter } from 'rxjs/operators';
constructor(private router: Router) {
// Create a new Observable that publishes only the NavigationStart event
this.navStart = router.events.pipe(
filter(evt => evt instanceof NavigationStart)
) as Observable;
}
- The `ActivatedRoute` is an injected router service that makes use of observables to get information about a route path and parameters.
```ts
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-routable',
templateUrl: './routable.component.html',
styleUrls: ['./routable.component.css']
})
export class Routable2Component implements OnInit {
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.url
.subscribe(url => console.log('The URL changed to: ' + url));
}
}
5.0 Reactive forms
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.
Angular makes use of
observables
as an interface to handle a variety of commonasynchronous operations
. For example:from a child to a parent
component.AJAX requests and responses
.listen for and respond to user-input events
.1.0 Transmitting data between components
EventEmitter
class that is used when publishing values from a component through the@Output() decorator
. EventEmitter extends RxJS Subject, adding anemit()
method so it can send arbitrary values. When you call emit(), it passes the emitted value to thenext()
method ofany subscribed observer
.2.0 HTTP
POST
,PUT
,GET
,DELETE
, etc3.0 Async pipe
The
AsyncPipe
subscribes to an observable or promise andreturns 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.
4.0 Router
Router.events
provides events as observables.@Component({ selector: 'app-routable', templateUrl: './routable.component.html', styleUrls: ['./routable.component.css'] }) export class Routable1Component implements OnInit {
navStart: Observable;
constructor(private router: Router) { // Create a new Observable that publishes only the NavigationStart event this.navStart = router.events.pipe( filter(evt => evt instanceof NavigationStart) ) as Observable;
}
ngOnInit() { this.navStart.subscribe(evt => console.log('Navigation Started!')); } }
5.0 Reactive forms
valueChanges
andstatusChanges
contain observables that raise change events. Subscribing to an observable form-control property is a way of triggering application logic within the component class.@Component({ selector: 'my-component', template: 'MyComponent Template' }) export class MyComponent implements OnInit { nameChangeLog: string[] = []; heroForm: FormGroup;
ngOnInit() { this.logNameChange(); } logNameChange() { const nameControl = this.heroForm.get('name'); nameControl.valueChanges.forEach( (value: string) => this.nameChangeLog.push(value) ); } }