Angular Observables Pipe Async

Observables provide support for passing messages between publishers and subscribers in your application. In the example below parent.component contains the child.component which binds to members counterSubject, countObservable$ and foo declared in the parent.

In the interpolated html the | async sets up and destroys the subscription for you. It is common practice for the observable to be suffixed with $, so here the observable is countObservable$

parent.component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
parent.component.ts

import ...
@Component({
...
})
export class ParentComponent implements OnInit {

private counterSubject = new BehaviorSubject<number>(0)
private countObservable$: Observable<number>
private foo = 'this is the text value of foo'
constructor() { }

ngOnInit() {
this.countObservable$ = this.counterSubject
}

inc() {
let _count = this.counterSubject.getValue() + 1
this.counterSubject.next(_count)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
parent-search.component.html

<h2>parent</h2>

<p> countObservable: {{countObservable$ | async}}</p>
<p> countSubject: {{counterSubject.getValue()}}</p>

<button (click)="inc()">+</button>

<hr>

<app-child
[foo]="foo"
[countObservable]="countObservable$"
[counterSubject]="counterSubject">
</app-child>

child.component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
child-control-search.component.ts

import ...
@Component({
...
})
export class ChildComponent implements OnInit {

@Input() foo : string;
@Input() countObservable : Observable<number>;
@Input() counterSubject : Observable<number>;

constructor() { }

ngOnInit() {
}

}
1
2
3
4
5
6
7
child.component.html

<h2>child</h2>

<p> foo: {{foo}}</p>
<p> countObservable: {{countObservable | async}}</p>
<p> countSubject: {{counterSubject | async}}</p>

Reference