在函数中使用管道运算符返回Observable

时间:2018-03-25 09:53:37

标签: angular typescript rxjs observable

我有一个函数返回Observable但是我想管道这个Observable并应用filter函数和interval每2秒发出一个Person。在这种情况下,任何人都可以告诉我pipe运算符是如何运作的吗?

PersonService.ts

 constructor() {
    this.initPersonArray();
  }

  init(): Observable<Person> {
    return Observable.create(obs => {
      this.persons.forEach(el => {
        obs.next(el);
      });
    });
  }

  initPersonArray(): Person[] {
    this.persons.push(
      new Person('Michal', 'Kowlaski', 24, new Array('plywanie', 'pilka nozna'), Sex.MALE),
      new Person('Stefan', 'Kowlaski', 20, new Array('plywanie', 'pilka nozna'), Sex.MALE),
      new Person('Jacek', 'Kowlaski', 54, new Array('plywanie', 'pilka nozna'), Sex.MALE),
      new Person('Małgorzata', 'Kowlaski', 52, new Array('plywanie', 'pilka nozna'), Sex.FEMALE),
      new Person('Katarzyna', 'Kowlaski', 84, new Array('plywanie', 'pilka nozna'), Sex.FEMALE),
      new Person('Jan', 'Kowlaski', 86, new Array('plywanie', 'pilka nozna'), Sex.MALE),
    );
    return this.persons;
  }  

然后在component中我通过

调用此函数
  ngOnInit(): void {
    this.personService.init().subscribe(res => {
      console.log('----->', res);
    });
  }  

1 个答案:

答案 0 :(得分:1)

简化示例:

ts文件

import { Component } from '@angular/core';
import { interval } from 'rxjs/observable/interval';
import { map, filter, take } from 'rxjs/operators'
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  person$: Observable<string>;

  people = [
    'Tomasz',
    'Piotr',
    'Anna',
    'Magda',
  ]

  ngOnInit() {
    this.person$ = interval(2000).pipe(
      take(this.people.length),
      map((i) => this.people[i]),
      filter(person => // ... filter by person prop)
    )
  }
}

html文件

<div> {{ person$ | async }} </div>

Live example