Angular5升级至Angular6后RxJS6相关报错问题求助
解决Angular 6升级后RxJS 6的常见问题
嘿,你遇到的这些问题都是RxJS 6从RxJS 5升级后的API变化导致的,别担心,我一步步帮你搞定:
问题1:map操作符报错(Property 'map' does not exist on type 'Observable<Object>')
你提到已经尝试导入map并改用pipe,但看你的Service代码里还在使用.map()的旧写法,需要彻底改成RxJS 6的管道写法:
- 正确导入
map操作符:在你的VariationService顶部添加:import { map } from 'rxjs/operators'; - 替换
.map()为pipe(map(...)):修改getFlowChart方法里的Observable调用,同时注意HttpClient返回的是响应体而非旧的Response对象,建议调整类型:return this.http.post( `${this.ip}/workflow`, { 'access_token': token, 'type': 'adjustment_workflow_get', 'data': { 'status': status } } ).pipe( map((res: any) => { if ( res['errcode'] !== '00000') { return []; } return res['datas']; }) );
问题2:Observable.of报错(rxjs__WEBPACK_IMPORTED_MODULE_1__.Observable.of is not a function)
RxJS 6里,of已经从Observable的静态方法变成了独立的创建函数,需要这样修改:
- 导入
of函数:在SelectivePreloadingStrategy文件顶部添加:import { Observable, of } from 'rxjs'; - 替换
Observable.of(null)为of(null):修改preload方法的else分支:return of(null);
额外注意事项
虽然你安装了rxjs-compat(用来兼容RxJS 5的API),但最好还是逐步迁移到RxJS 6的标准写法,这样能避免后续版本的兼容问题。如果还有其他类似的操作符(比如switchMap、filter等),都需要改成从rxjs/operators导入,然后用pipe包裹调用。
修改后的完整代码示例
VariationService.ts
import { Injectable } from '@angular/core'; import {environment} from '../../environments/environment'; import {HttpClient} from '@angular/common/http'; import {StorageService} from '../services/storage.service'; import { map } from 'rxjs/operators'; @Injectable() export class VariationService { ip = environment.url.management; constructor(private http: HttpClient, private storageService: StorageService) { } getFlowChart(status?) { status = status ? status : ''; let token = this.storageService.getToken('token'); return this.http.post( `${this.ip}/workflow`, { 'access_token': token, 'type': 'adjustment_workflow_get', 'data': { 'status': status } } ).pipe( map((res: any) => { if ( res['errcode'] !== '00000') { return []; } return res['datas']; }) ); } }
SelectivePreloadingStrategy.ts
import {Injectable} from '@angular/core'; import { PreloadingStrategy, Route } from '@angular/router'; import { Observable, of } from 'rxjs'; @Injectable() export class SelectivePreloadingStrategy implements PreloadingStrategy { preloadedModules: string[] = []; preload(route: Route, load: () => Observable<any>): Observable<any> { if (route.data && route.data['preload']) { this.preloadedModules.push(route.path); return load(); } else { return of(null); } } }
按这个修改后,你的RxJS相关报错应该就能全部解决啦!
内容的提问来源于stack exchange,提问作者Tinaaulim
相关产品推荐
相关产品推荐

