简体   繁体   English

Angular2:Guard中的嵌套Observable

[英]Angular2: Nested Observables in Guard

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. canActive方法中,我需要发出两个http请求,根据第一个响应触发第二个请求。 However, the second request is never made and I assume it is about the nested construct of returning Observables. 但是,第二个请求永远不会发生,我认为它是关于返回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      );
     }
   );  
 }

Both getA() and getB() return the following: getA()和getB()都返回以下内容:

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

}; };

The code is simplified, but you may assume that getA() and getB() work properly. 代码已简化,但您可以假设getA()和getB()正常工作。 getA() is sent alright over the network when the Guard is called, getB() is never sent, though. 调用Guard时,getA()在网络上发送,但是从不发送getB()。 The debugger exits silently in line 5. 调试器在第5行静默退出。

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: 还有一件事,TypeScript显示了一个可能已经告诉我解决方案的警告,但是,我太多了Noob with Observables特别知道如何处理它:

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

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. 为了猜测,Observables的构造永远不会解决,这就是没有警告的原因,我等到时间结束。 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. 我天真的想法是,只要任何Observable都返回一个布尔值(如第7行所做),订阅者就会知道如何处理它。

I'm happy to read your hints. 我很高兴看到你的提示。 Off to bed... 去睡觉了...

You should use switchMap here: 你应该在这里使用switchMap

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

In your code, you are creating an Observable of Observables. 在您的代码中,您正在创建一个Observable of Observables。 switchMap flattens that structure and emits the emitted items of B through A. switchMap平该结构并发出B到A的发射项。

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

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