我有一个函数返回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);
});
}
答案 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>