2017-08-01 69 views
1

我有一个角度4应用程序。在这个应用程序中,我有一个PayPal服务,它执行一些服务器工作并导航(从客户端)到PayPal。RxJs - 订阅可观察到的最后的地方


 
@Injectable() 
 
export class PaypalService { 
 
    private readonly http: HttpApi; 
 

 
    constructor(private readonly httpFactory: HttpFactoryService) { 
 
    this.http = httpFactory.get(HttpRequestType.Secured); 
 
    } 
 

 
    checkout(transactionId: string): 
 
    Observable<Response> { 
 
    let subscriber = this.http.post(environment.paymentServer + '/pay', {transactionId: transactionId}) 
 
    subscriber.subscribe((response:Response) => { 
 
     let result = response.json(); 
 
     window.location.href = result.paymentUrl; 
 
    }); 
 
    return subscriber; 
 
    } 
 
}

我希望所有的用户被告知后,才window.location.href将被调用。

paypal.checkout("1234").subscribe(() => 
 
//This code should be called before the navigation will start 
 
doSomeCleaning())

我知道我可以使用延迟,但我不知道是否有一个更好的选择。

+0

尝试与'flatMap'运营商都流映射例如,在年底只有一个订阅方法,从中可以调用重定向。 –

回答

0

由于您需要强制观察者以特定的顺序被呼叫,您不应该依赖他们的订阅顺序。最简单的方法是使用setTimeout()没有任何延迟:

observable.subscribe((response:Response) => { 
    let result = response.json(); 
    setTimeout(() => window.location.href = result.paymentUrl); 
}); 

或者,也许更好,更的Rx的方式,可以使用observeOn运营商和async调度发出值到另一个JS事件的首次观测。

import { async } from 'rxjs/scheduler/async'; 

... 

let observable = ... 
observable.observeOn(async).subscribe(...); 

return observable; 
+0

谢谢你的帮助。您能否详细解释一下异步解决方案? –

+0

你想知道什么? – martin

+0

什么是observable.observeOn(异步)会做什么? –

0

你为什么不就在回调重定向如下:

+0

我不希望其他组件知道有关PayPal的导航 –