Jan Testowy
Jan Testowy

Reputation: 667

Using pipe operator in function which returns Observable

I have a function which returns Observable but I want to pipe this Observable and apply filter function and interval to emit one Person each 2 seconds. Can anyone tell me how excatly pipe operator works in this case?

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;
  }  

Then in component I call this function by

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

Upvotes: 0

Views: 2999

Answers (1)

Tomasz Kula
Tomasz Kula

Reputation: 16837

Simplilfied example:

ts file

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 file

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

Live example

Upvotes: 1

Related Questions