【问题标题】:Not able to use filter operators of rxjs in angular4无法在 angular4 中使用 rxjs 的过滤器运算符
【发布时间】:2019-04-30 21:15:11
【问题描述】:

我正在尝试在 Angular 4 中使用过滤器,这是我的代码

import { Component, OnInit } from '@angular/core';
import { range } from 'rxjs/observable/range';
import { map, scan, filter, tap } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {  

  ngOnInit(){
    this.rxjs();
  }
  rxjs(){
    const source$ = range(1, 10);

    source$.pipe(
      filter(n => n % 2 !== 0), 
      tap(n => console.log('filtered value: ' + n)),
      map(n => n * n),
      tap(n => console.log('squared value: ' + n)),
      scan((acc,s) => acc + s, 0)
    )
    .subscribe(v => console.log(`sum of squared values : ${v}`));    
  }    
}

这是我使用 ng --version 命令发现的 Angular 版本

@angular/cli: 1.4.10
node: 8.9.1
os: win32 x64
@angular/animations: 4.4.7
@angular/common: 4.4.7
@angular/compiler: 4.4.7
@angular/core: 4.4.7
@angular/forms: 4.4.7
@angular/http: 4.4.7
@angular/platform-browser: 4.4.7
@angular/platform-browser-dynamic: 4.4.7
@angular/router: 4.4.7
@angular/cli: 1.4.10
@angular/compiler-cli: 4.4.7
@angular/language-service: 4.4.7
typescript: 2.3.4

但是当我编译时,我得到一个这样的错误

E:/angular-mock/routes/src/app/app.component.ts (19,19) 中的错误: 算术运算的左侧必须是“any”类型, 'number' 或枚举类型。

谁能帮我解决我在这方面做错了什么

【问题讨论】:

标签: angular rxjs5 rxjs-pipeable-operators


【解决方案1】:

您需要安装 RxJS 才能使用这个库

$ npm i rxjs

如果您需要向后兼容性用于未升级到版本 6 但也使用紧凑的旧项目或依赖项

$ npm i rxjs-compat

阅读详细的迁移指南:

https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md

演示:

$ npm i rxjs rxjs-compat

另见:

https://rxjs-dev.firebaseapp.com

https://github.com/ReactiveX/rxjs

【讨论】:

    【解决方案2】:

    我通过安装解决了这个问题 rxjs@6 并安装 rxjs-compat@6 以实现向后兼容性

     npm install rxjs@6 rxjs-compat@6 --save
    

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 2023-03-10
      • 2016-12-02
      • 2018-06-16
      • 2019-04-28
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2013-06-11
      相关资源
      最近更新 更多