Search code examples
angulartypescriptrxjscombinelatest

Angular how to use combineLatest to combine routes and queries from website url bar


Im trying to get the route and queries from the url bar. The below code is from a tutorial by CodeWithMosh. I am getting compile error at the combineLatest method.

The error is as follow:

(property) paramMap: Observable Argument of type '{ paramMap: Observable; queryParamMap: Observable; }' is not assignable to parameter of type 'ObservableInput'.
Object literal may only specify known properties, and 'paramMap' does not exist in type 'ObservableInput'

I am a newbie in angular and I'm not sure what does the error mean and I have tried following this stack overflow answer but I still got the error. Thank you.

The full code is as below:

    import { ActivatedRoute } from '@angular/router';
    import { GithubFollowersService } from './../services/github-followers.service';
    import { Component, OnInit } from '@angular/core';
    import 'rxjs/add/Observable/combineLatest';
    import { Observable } from 'rxjs/internal/Observable';
    import { combineLatest } from 'rxjs';

    @Component({
      selector: 'github-followers',
      templateUrl: './github-followers.component.html',
      styleUrls: ['./github-followers.component.css']
    })
    export class GithubFollowersComponent implements OnInit {
      followers : any[];

      constructor(
        private route: ActivatedRoute,
        private service : GithubFollowersService) { }

      ngOnInit() {
        const paramMap = this.route.paramMap;
        const queryParamMap = this.route.queryParamMap;

        combineLatest({
          paramMap, // error here
          queryParamMap
        })
        .subscribe(combined => {
          let id = combined[0].get('id');//the 0 means the 1st 1 which is paramMap from above
          let page = combined[1].get('page');

          this.service.getAll().subscribe(followers => this.followers = followers);
        });


      }

    }

Solution

  • If you are using the current version of Angular/RxJS, your imports should look like this:

    import { combineLatest, Observable } from 'rxjs';
    

    The error you see is incorrect syntax for combineLatest. It should look like this:

      combineLatest([
        paramMap,
        queryParamMap
      ])
    

    Notice the [] instead of the {}

    Also, it is a convention to suffix variables containing an Observable with a $.

    From the github comments:

    Static version of combineLatest accepts either an array of Observables or each Observable can be put directly as an argument.

    Link here: https://github.com/ReactiveX/rxjs/blob/95bd8073e33c39a8f8d4ade8bf15c39a1154a879/src/internal/observable/combineLatest.ts