How to create a new observable subscription based on existing observables in rxjs?

I need to do something like the following line in my project (from https://github.com/devyumao/angular2-busy )

ngOnInit() {
    this.busy = this.http.get('...').subscribe();
}

In my project, I make a request based on a route change as follows:

ngOnInit(): void {   
    this.activatedRoute
        .params
        .map(params => params['queryString'])
        .flatMap(id => this.http.(''))
        .subscribe(result => this.data = result);   
}

It seems I need to create a new subscription every time a route change occurs. I am not sure how to do this.

I am only looking for rxjs solution (without using Promise).

Thank!

Derek

+4
source share
2 answers

Actually, you can subscribe to ajaxCallObservable in the chain. :)

ngOnInit(): void {   
    this.activatedRoute
        .params
        .map(params => params['queryString'])
        .map(id => this.http.(''))
        .do(ajaxCallObservable => { this.busy = ajaxCallObservable.subscribe() })
        .flatMap(ajaxCallObservable => ajaxCallObservable)
        .subscribe(result => this.data = result);   
}
Run code
+2
source

(, ) :

this.router.events
  .filter(event => event instanceof NavigationStart)
  // or NavigationEnd
  .subscribe(event => {
    this.http.post('').subscribe();
  });

.

, ActivateRoute params.

combineLatest Observable, :

export class AppComponent {

  constructor(private router: Router, private route: ActivatedRoute) {
    Observable.combineLatest(
      this.router.events
        .filter(event => event instanceof NavigationStart),
      this.route.params
    )
    .subscribe(data => {
      const event = data[0];
      const params = data[1];
      (...)
    });
  }
}

:

import 'rxjs/add/observable/combineLatest';
+4

Source: https://habr.com/ru/post/1678806/


All Articles