Javascript 问:Angular2:类型“Observable<Params>”上不存在“switchMap”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42549115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:14:52  来源:igfitidea点击:

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

javascriptangular

提问by Sean.huang

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:

我正在学习 Angular2,并按照“英雄之旅”示例,当我设置路由的详细信息页面时,我从 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,

我正在使用 webpack 来管理包的东西,

below is the JS code:

下面是JS代码:

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:

包.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:

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:

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));
    }

}

采纳答案by Sean.huang

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);
      } 
    });

回答by Amit Portnoy

You need to import the switchMapoperator:

您需要导入switchMap运算符:

import 'rxjs/add/operator/switchMap';

import 'rxjs/add/operator/switchMap';

update for rxjs >=5.5.0:

rxjs >=5.5.0 的更新:

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

对于 [email protected] 或更高版本,建议使用管道运算符而不是扩充:

import { switchMap } from 'rxjs/operators';

\...

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

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

(这避免了副作用并实现更好的包大小优化)

回答by aakashsingh461

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)

        }

      }));

    } 

回答by Ian Samz

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

随 rxjs 6.xx 一起提供的 Angular 6 更新

import { switchMap } from 'rxjs/operators';

Then simply wrap you switchMap with a pipe operator.

然后简单地用管道操作符包装你的 switchMap。

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

回答by Sebastian Brestin

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);
}

回答by An Nguyen

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

rxjs> 6.xx 随附的 Angular 7 更新

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

从 'rxjs/operators' 导入 { switchMap }; 然后简单地用管道操作符包装你的 switchMap。

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

回答by naz786

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 switchMapeven though I am using the import: import 'rxjs/add/operator/switchMap';.

我正在 Visual Studio 中进行开发,并且还在此处的 Angular 文档中遵循 Angular2 教程的相同部分:https://angular.io/docs/ts/latest/tutorial/toh-pt5.htmlswitchMap即使我使用了 import: ,也会出现相同的错误import 'rxjs/add/operator/switchMap';

I realised that my app wasn't loading for me because the .htmlfiles were in the src/appfolder - 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.htmland dashboard.component.htmlto the /srcfolder and then the app began to show the correct results in the browser.

我意识到我的应用程序没有为我加载,因为.html文件在src/app文件夹中 - 即使 Angular 教程告诉您将它们留在该目录中。没有人告诉我这样做 - 这只是偶然 - 我将hero-detail.component.html和移动dashboard.component.html/src文件夹,然后应用程序开始在浏览器中显示正确的结果。