2017-08-01 126 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的導航 –