Here we have to classes GetDataAsyncService which waits for change in the store (and not executes the block of code under it until a change in the store ( this.getDataAsyncService.getAsyncData().subscribe((data)=>{ )}). When it is called from MainComponent it will get return of(propA); (from GetDataAsyncService) before the block of code in the listener is executed – because the listener is still waiting for a change in the store. I want to emit that observable only when that operation block is executed.
JavaScript
x
32
32
1
export class GetDataAsyncService {
2
propA;
3
constructor(private store: Store<AppState>)
4
5
getData():Observable<any>{
6
this.store.pipe(select(appState)).subscribe((val)=>{
7
// operation block
8
// some operations
9
// some more operations
10
this.propA = val.propA;
11
})
12
return of(propA); // this should be emitted with the latest value only when the block of code above executes - not before that
13
}
14
15
16
17
}
18
19
export MainComponent implenents OnInit{
20
propA: string = '';
21
constructor(private getDataAsyncService: GetDataAsyncService){}
22
23
ngOnInit(): void{
24
this.getDataAsyncService.getAsyncData().subscribe((data)=>{
25
this.propA = data.propA;
26
})
27
}
28
// any operation involving propA
29
// code ......
30
31
}
32
Advertisement
Answer
You can achieve that by returning the Observable
itself from the getData
function and mapping it to the required prop, instead of subscribe
to it, like the following:
JavaScript
1
23
23
1
export class GetDataAsyncService {
2
propA;
3
constructor(private store: Store<AppState>) {}
4
5
getData(): Observable<any> {
6
return this.store.pipe(
7
select(appState),
8
map((val) => val.propA)
9
);
10
}
11
}
12
13
export class MainComponent implements OnInit {
14
propA: string = '';
15
constructor(private getDataAsyncService: GetDataAsyncService) {}
16
17
ngOnInit(): void {
18
this.getDataAsyncService.getAsyncData().subscribe((propA) => {
19
this.propA = propA;
20
});
21
}
22
}
23