Sean.huang
Sean.huang

Reputation: 456

Q: Angular2: 'switchMap' does not exist on type 'Observable<Params>'

I am learning Angular2, and following the "Tour of Heroes" example, when I setup a detail page for routing, I got this compile error from webpack:

ERROR in ./ts/router/route-hero-detail.component.ts
(25,23): error TS2339: Property 'switchMap' does not exist on type 'Observable<Params>'.

I'm using the webpack to manage the package thing,

below is the JS code:

import 'rxjs/add/operator/switchMap';
import { Component, OnInit }      from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location }               from '@angular/common';

import { Hero }         from '../hero';
import { HeroService }  from '../hero.service';
@Component({
  moduleId: module.id,
  selector: 'my-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: [ './hero-detail.component.css' ]
})
export class RouteHeroDetailComponent implements OnInit {
  hero: Hero;
 
  constructor(
    private heroService: HeroService,
    private route: ActivatedRoute,
    private location: Location
  ) {}

  ngOnInit(): void {
      
    this.route.params.switchMap((params: Params) => this.heroService.getHero(+params['id']))
      .subscribe((hero: Hero) => this.hero = hero);   
  } 

  goBack(): void {
    this.location.back();
  }
}

package.json:

{
  "name": "environment",
  "version": "1.0.0",
  "description": "I will show you how to set up angular2 development environment",
  "keywords": [
    "angular2",
    "environment"
  ],
  "scripts": {
    "start": "webpack-dev-server --hot--host 0.0.0.0"
  },
  "author": "Howard.Zuo",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "^2.4.5",
    "@angular/compiler": "^2.4.5",
    "@angular/core": "^2.4.5",
    "@angular/forms": "^2.4.5",
    "@angular/platform-browser": "^2.4.5",
    "@angular/platform-browser-dynamic": "^2.4.5",
    "@angular/router": "^3.4.8",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0-alpha.20",
    "@types/node": "^7.0.5",
    "bootstrap": "^4.0.0-alpha.6",
    "core-js": "^2.4.1",
    "rxjs": "5.0.3",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@types/core-js": "^0.9.35",
    "ts-loader": "^2.0.0",
    "typescript": "^2.1.5",
    "webpack": "^2.2.0",
    "webpack-dev-server": "^2.2.0"
  }
}

webpack.config.js:

const path = require('path');

module.exports = {
    entry: {
        index: "./ts/index.ts"
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: 'dist/'
    },
    module: {
        exprContextCritical: false,
        rules: [
            {
                test: /\.ts$/,
                use: ['ts-loader']
            }
        ]
    },
    resolve: {
        extensions: [
            '.js',
            '.ts'
        ]
    }
};

HeroService.ts:

import {Injectable} from '@angular/core';
import {Hero} from './hero';
import {HEROES} from './mock-heroes';
import { Observable } from 'rxjs/Observable'; 

@Injectable()
export class HeroService {
	
    getHeroes() : Promise<Hero[]>{
    return Promise.resolve(HEROES);
  }

	  getHero(id: number): Promise<Hero> {
      return this.getHeroes()
               .then(heroes => heroes.find(hero => hero.id === id));
    }

}

Upvotes: 36

Views: 30173

Answers (7)

An Nguyen
An Nguyen

Reputation: 163

The Angular 7 Update Which comes with rxjs> 6.x.x you

import { switchMap } from 'rxjs/operators'; Then simply wrap you switchMap with a pipe operator.

this.route.params.pipe(switchMap((params: Params) =>
  this.heroService.getHero(+params['id'])))
.subscribe((hero: Hero) => {this.hero = hero}); 

Upvotes: 2

aakashsingh461
aakashsingh461

Reputation: 121

import { Observable, of } from 'rxjs';

import { switchMap } from 'rxjs/operators';   


this.user = this.afAuth.authState.pipe(switchMap(user => {

        if (user) {

          return this.afs.doc<User>(`users/${user.uid}`).valueChanges()

        } else {

          return of(null)

        }

      }));

    } 

Upvotes: 12

Ian Samz
Ian Samz

Reputation: 2119

The Angular 6 Update Which comes with rxjs 6.x.x you

import { switchMap } from 'rxjs/operators';

Then simply wrap you switchMap with a pipe operator.

this.route.params.pipe(switchMap((params: Params) => {
  this.heroService.getHero(+params['id'])
})).subscribe((hero: Hero) => this.hero = hero); 

Upvotes: 6

Sebastian Brestin
Sebastian Brestin

Reputation: 503

import { ActivatedRoute, Params }   from '@angular/router';
import { switchMap } from 'rxjs/operators';
...
ngOnInit(): void {
  this.route.params.pipe(
    switchMap(
      (params: Params) =>
       this.heroService.getHero(+params['id'])))
    .subscribe(hero => this.hero = hero);
}

Upvotes: 2

Amit Portnoy
Amit Portnoy

Reputation: 6336

You need to import the switchMap operator:

import 'rxjs/add/operator/switchMap';

update for rxjs >=5.5.0:

for [email protected] or higher it's recommended to use the pipe operator instead of augmentation:

import { switchMap } from 'rxjs/operators';

\\...

this.route.params.pipe(switchMap((params: Params) => /*... */))
  .subscribe(/*... */);
\\...

(this avoids side effects and enable better bundle size optimization)

Upvotes: 74

naz786
naz786

Reputation: 495

I'm developing in Visual Studio and also following the same bit of the Angular2 tutorial in the Angular documentation here: https://angular.io/docs/ts/latest/tutorial/toh-pt5.html, and I get the same errors showing up for switchMap even though I am using the import: import 'rxjs/add/operator/switchMap';.

I realised that my app wasn't loading for me because the .html files were in the src/app folder - even though the Angular tutorial tells you to leave them in that directory. Nobody told me to do this - it was just by chance - that I moved both the hero-detail.component.html and dashboard.component.html to the /src folder and then the app began to show the correct results in the browser.

Upvotes: 1

Sean.huang
Sean.huang

Reputation: 456

This issue has been fixed, check below:

    this.route.params.forEach((params: Params) => {
      if (params['id'] !== undefined) {
        let id = +params['id'];
        this.heroService.getHero(id)
            .then(hero => this.hero = hero);
      } 
    });

Upvotes: 7

Related Questions