Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable.forkJoin of Angular Route Params Observable

Tags:

angular

rxjs

In my Angular component ngOnInit() I want to:

  1. Read route parameter and execute a dependent HTTP call with it as argument.
  2. Execute separate HTTP call.
  3. Wait for both HTTP calls to finish.

Both HTTP calls are always executing, but when my first observable is wired up to route.params, the forkJoin(...).subscribe(...) method never runs. If I replace this.route.params with Observable.of({id: 1234}) forkJoin().subscribe() gets called properly.

// 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 => { ... },
        () => { ... }
    );
like image 379
Jeff Swensen Avatar asked Mar 10 '17 19:03

Jeff Swensen


People also ask

What are observables in angular?

Observables provide support for passing messages between parts of your application. They are used frequently in Angular and are the recommended technique for event handling, asynchronous programming, and handling multiple values.

How to pass route params in angular?

Angular Route Params: How to Pass Route Params in Angular. To access route parameters and query parameters in Angular, use ActivatedRoute service. The ActivatedRoute service provides Observables through which we can subscribe to the values of route params and route query params. In Angular, we can pass the data as route parameters in two ways.

What is forkjoin in Angular 2?

That is now an array of Observables. forkJoin is added as a wrapper in order for those calls to be made The end result can then be subscribed to which will output as a single array with the same count of items. NOTE: If one call fails in a forkJoin, THEY WILL ALL FAIL.

How to pass values from one view to another in angular?

In Angular, we can pass the data as route parameters in two ways. Route params(Route parameters) Route queryParams(Route query parameters) If we want to pass values between views, then we can use route params. For example, if we’re going to pass an ID from one route to another and fetch the id on a component onInit(), then we can use route params.


1 Answers

My guess is route.params is never completed. That's why forkJoin does not work. You can use combineLatest instead of forkJoin

like image 114
Robin Dijkhof Avatar answered Oct 29 '22 17:10

Robin Dijkhof