Angular2:守卫中的嵌套可观察对象 [英] Angular2: Nested Observables in Guard

查看:100
本文介绍了Angular2:守卫中的嵌套可观察对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个守卫某条路线的守卫.在canActive方法中,我需要发出两个http请求,根据第一个请求的响应触发第二个http请求.但是,第二个请求永远不会发出,我假设它是关于返回Observables的嵌套结构的.

I have a Guard protecting a certain route. In the canActive method I need to make two http requests, at which the second one is triggered based on the response of the first one. However, the second request is never made and I assume it is about the nested construct of returning Observables.

1 canActivate(route: ActivatedRouteSnapshot,
2          state: RouterStateSnapshot) : Observable<boolean>|boolean {
3  return this.provider.getA().map(
4    dataA => {
5      return this.provider.getB().map(
6        dataB => {
7          return (dataB.allowed);
8        }
9      );
     }
   );  
 }

getA()和getB()都返回以下内容:

Both getA() and getB() return the following:

getA() : Observable<any> {
  return this.http.post(URL,payload).
                   map(response => response.json());

};

代码已简化,但是您可以假定getA()和getB()正常工作.当调用Guard时,会通过网络正确发送getA(),但永远不会发送getB().调试器在第5行中静默退出.

The code is simplified, but you may assume that getA() and getB() work properly. getA() is sent alright over the network when the Guard is called, getB() is never sent, though. The debugger exits silently in line 5.

还有一件事,TypeScript显示了一个警告,它可能已经告诉了我解决方案,但是,我对Observables实在是个菜鸟,不知道该怎么做:

One more thing, TypeScript shows a warning that probably tells me solution already, however, I'm too much a Noob with Observables in particular to know what to do with it:

Observable<Observable<boolean>>' is not assignable 
to type 'Observable<boolean>'

要猜测一下,Observables的构造永远都无法解决,这就是为什么没有警告的原因,而我等到时间的尽头.我的天真想法是,只要任何Observable都将返回布尔值(如第7行中所述),订阅者就会知道如何处理它.

To make a guess, the construct of Observables never resolves, that's why there is no warning and I wait until the end of time. My naive notion was that, as long as any Observable will return a boolean (as done in line 7), the subscriber would know how to handle it.

我很高兴阅读您的提示.上床睡觉...

I'm happy to read your hints. Off to bed...

推荐答案

您应在此处使用switchMap:

return this.provider.getA().switchMap(
  dataA => {
    return this.provider.getB().map(
      dataB => {
        return (dataB.allowed);
      }
    );
  }
);

在您的代码中,您正在创建一个Observable of Observables. switchMap展平该结构并通过A发射B的发射物.

In your code, you are creating an Observable of Observables. switchMap flattens that structure and emits the emitted items of B through A.

这篇关于Angular2:守卫中的嵌套可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆