【问题标题】:Array iterating with` Rxjs` filter and map使用 Rxjs 过滤器和映射进行数组迭代
【发布时间】:2021-10-07 04:33:03
【问题描述】:

使用映射和过滤器迭代array 的正确方法是什么?目前两者都期望单一值。但我的Observable 带有数组。请告诉我正确的方法。

这是我的 ts:

import { Component, OnInit } from '@angular/core';
import { Observable, of } from 'rxjs';
import { filter, map, tap} from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {

  name = 'Angular';
  ranks:Observable<number[]>;
  rankList$:Observable<number[]>;

  constructor(){
    this.ranks = of([1,2,3,4,5]);
  }

  ngOnInit(){
    this.rankList$ = this.ranks.pipe(
      filter(n => n % 2 !== 0), map((num:number[]) => num)
      )
  }
}

得到一个错误:

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.(2362)
(parameter) n: number[]

Live Demo

【问题讨论】:

    标签: angular rxjs rxjs-pipeable-operators


    【解决方案1】:

    我认为您在数组过滤器和observable filter 之间混合使用,可观察过滤器将应用于发出的值,在您的情况下是整个数字数组,因此您得到的错误,可观察过滤器将检查发射到可观察和如果条件为真,它将继续发射,如果这是您的目标,则可观察过滤器中的条件应应用于作为数组的发射类型,但如果您尝试过滤发射的数组并仅发射 Odd值,那么 map 就是你应该使用的。

    this.rankList$ = this.ranks.pipe(
      map((num: number[]) => num.filter(n => n % 2 !== 0))
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 2017-07-18
      • 1970-01-01
      • 2019-06-26
      • 2020-04-18
      相关资源
      最近更新 更多