【问题标题】:Q: Angular2: 'switchMap' does not exist on type 'Observable<Params>'问:Angular2:'switchMap' 在类型'Observable<Params>' 上不存在
【发布时间】:2017-03-02 07:22:28
【问题描述】:

我正在学习 Angular2,并按照“英雄之旅”示例,当我设置路由的详细信息页面时,我从 webpack 收到此编译错误:

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

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

下面是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:

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

}

【问题讨论】:

  • 你可以尝试在其他导入之后导入 import 'rxjs/add/operator/switchMap';
  • 谢谢,但它不起作用...同样的错误。
  • 你能分享你的英雄服务吗?
  • 从'@angular/core'导入{Injectable};从'./hero'导入{英雄};从'./mock-heroes'导入{HEROES}; @Injectable() 导出类 HeroService { getHeroes() : Promise{ return Promise.resolve(HEROES); } getHero(id: number): Promise { return this.getHeroes() .then(heroes => heros.find(hero => hero.id === id)); } }
  • 对不起,我不知道如何格式化注释中的代码..

标签: javascript angular


【解决方案1】:

需要导入switchMap操作符:

import 'rxjs/add/operator/switchMap';

rxjs 更新 >=5.5.0:

对于 rxjs@5.5.0 或更高版本,建议使用管道运算符而不是扩充:

import { switchMap } from 'rxjs/operators';

\\...

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

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

【讨论】:

【解决方案2】:
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)

        }

      }));

    } 

【讨论】:

  • 只包含代码的答案不被认为是完整的。
  • 亲,你可以导入switchMap算子试试看。
【解决方案3】:

此问题已修复,请查看以下内容:

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

【讨论】:

  • 你也可以使用this.route.params.filter(params =&gt; params['id'] !== undefined).forEach((params: Params) =&gt; {
  • 谢谢,我把这个放进去。
  • 我被困在 Angular 文档“路由”部分的同一个教程上。有没有发现为什么 switchMap() 不能被导入?另外,您是从哪里提出这个解决方案的?
  • 如果我这样做,我会收到错误消息:“类型 'Hero' 上不存在属性 'then'”。
【解决方案4】:

rxjs 6.x.x 自带的 Angular 6 更新

import { switchMap } from 'rxjs/operators';

然后简单地用管道运算符包装你的 switchMap。

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

【讨论】:

    【解决方案5】:
    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);
    }
    

    【讨论】:

      【解决方案6】:

      rxjs 附带的 Angular 7 更新> 6.x.x 你

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

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

      【讨论】:

        【解决方案7】:

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

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

        【讨论】:

          猜你喜欢
          • 2018-07-30
          • 2016-10-26
          • 1970-01-01
          • 2018-08-17
          • 2020-10-10
          • 1970-01-01
          • 2023-03-26
          • 2016-12-31
          • 1970-01-01
          相关资源
          最近更新 更多