Observable.forkJoin of Angular Route parameter observes

In my Angular component, ngOnInit()I want:

  • Read the route parameter and make a dependent HTTP call with it as an argument.
  • Make a separate HTTP call.
  • Wait for both HTTP calls to complete.

Both HTTP calls are always made, but when my first observable is connected before route.params, the method forkJoin(...).subscribe(...)never starts. If I replaced this.route.paramswith Observable.of({id: 1234}) forkJoin().subscribe(), it is called correctly.

// VERSION 1 forkJoin().subscribe() never gets called
var dependentObservable = this.route.params
    .switchMap(params => {
        this.myId = +params['id'];
        return this.myService.getMyInfo(this.myId);
    });

// VERSION 2 forkJoin().subscribe gets called
var dependentObservable = Observable.of({id: 123})
    .switchMap(params => {
        this.myId = +params['id'];
        return this.myService.getMyInfo(this.myId);
    });

var independentObservable = this.myService.getOtherInfo();

Observable.forkJoin([dependentObservable, independentObservable])
    .subscribe(
        results = { ... },
        error => { ... },
        () => { ... }
    );
+4
source share
2 answers

My hunch route.paramsnever ends. That is why it forkJoindoes not work. You can use combineLatestinsteadforkJoin

+8
source

doc forkJoin , .

Observable.of({id: 123}) 

{id: 123}

this.route.params

. , . .

, take (1):

 this.route.params.take(1)

, , combLatest

Observable.combineLatest(dependentObservable, independentObservable)
+4

Source: https://habr.com/ru/post/1672022/


All Articles