简体   繁体   English

如何根据rxjs中现有的observable创建一个新的可观察订阅?

[英]how to create a new observable subscription based on existing observable in rxjs?

I need to do something as the following line in my project(from https://github.com/devyumao/angular2-busy ) 我需要在我的项目中执行以下操作(来自https://github.com/devyumao/angular2-busy

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

In my project, I am making request based on route change as the following: 在我的项目中,我根据路线变化提出以下要求:

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 there is a change in route. 似乎每次路线发生变化时我都需要创建一个新的订阅。 I am not sure how to do it. 我不知道该怎么做。

I am looking for rxjs solution only (without using Promise). 我只在寻找rxjs解决方案(不使用Promise)。

Thanks! 谢谢!

derek 德里克

I would globally (in your main component for example) register on route changes this way and trigger your request in the associated callback: 我会全局(在您的主要组件中)以这种方式注册路由更改并在相关的回调中触发您的请求:

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

This way you subscribe once on changes. 这样您就可以订阅一次更改。

If you want to have access to route params, you need to inject the ActivateRoute instance as well and subscribe on its params attribute. 如果您想要访问路径参数,则还需要注入ActivateRoute实例并订阅其params属性。

For this, I would leverage the combineLatest method of the Observable class, like described below: 为此,我将利用Observable类的combineLatest方法,如下所述:

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];
      (...)
    });
  }
}

Don't forget to add this: 别忘了添加这个:

import 'rxjs/add/observable/combineLatest';

Actually, you can subscribe to the ajaxCallObservable in the chain. 实际上,您可以订阅链中的ajaxCallObservable。 :) :)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM