首页 > 解决方案 > 'Observable' 类型上不存在属性 'do''

问题描述

升级到 Angular 6.0 和 Rxjs 到 6.0 后,我收到以下编译错误:

Property 'do' does not exist on type 'Observable'.

这是代码:

import { Observable, of } from 'rxjs';
import 'rxjs/add/operator/do';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import { IProduct } from './product';

@Injectable()
export class ProductService { 
    constructor(
        private product: IProduct)
    {         
    }

    getProduct = () => { 
        return product.products
            // error on next line
            .do(data => console.log('All:' + JSON.stringify(data)))
            .catch(this.handleError);
    }

    private handleError(err: HttpErrorResponse) { 
        console.log(err.message);
        return Observable.throw(err.message);        
    }
}

任何想法?

标签: angularrxjs6

解决方案


问题不在于角度,而在于 rxjs。rxjs 引入了 rxjs 版本 6 的重大更改。

要让您的代码在不更改任何代码的情况下再次运行,请安装以下软件包:

npm install rxjs-compat@6 --save

然后,您应该能够编译您的项目。rxjs-compat旨在作为临时解决方案,因此您需要更新代码库以使用新版本。


新的导入路径

您需要更新的内容:

  1. 更新导入语句

    import { Observable } from "rxjs/Observable";

    import { Observable } from "rxjs";

  2. 更新您的运营商进口自

    import 'rxjs/add/operator/do'

    import { do } from "rxjs/operators";


重命名运算符

由于与 JavaScript 保留字的名称冲突,一些运算符也已重命名。他们是

  1. do=>tap

  2. catch=>catchError

  3. switch=>switchAll

  4. finally=>finalize


没有运算符链接

你也不能再链接你的运营商了,你需要使用pipe运营商,例如

// an operator chain
source
  .map(x => x + x)
  .mergeMap(n => of(n + 1, n + 2)
    .filter(x => x % 1 == 0)
    .scan((acc, x) => acc + x, 0)
  )
  .catch(err => of('error found'))
  .subscribe(printResult);
// must be updated to a pipe flow
source.pipe(
  map(x => x + x),
  mergeMap(n => of(n + 1, n + 2).pipe(
    filter(x => x % 1 == 0),
    scan((acc, x) => acc + x, 0),
  )),
  catchError(err => of('error found')),
).subscribe(printResult);

推荐阅读