2017-08-28 27 views
0

我對Angular 4和Observables以及與它相關的所有東西都很陌生。 我試圖一個接一個地執行兩個http請求(只有第一個成功)。Angular(4):帶有Observable的多個HTTP請求:一個接一個成功

我使用這個代碼:

public getCompany(id: string): any { 
    let company = null; 

    this.authService.isValidUser().subscribe(response => { 
     const token = this.tokenStorageService.getTokenFromStorage(); 
     const requestUrl = environment.gatewayUrl + environment.companyService + environment.getCompanyEndPoint + id; 
     const headers = new Headers(); 
     headers.set('Authorization', 'Bearer ' + token); 
     const options = new RequestOptions({headers: headers}); 

     return this.http.get(requestUrl, options).catch(this.errorService.handleError); 

    }, (error: AppError) => { 
     // ........ // 
    }); 
    } 

這是isValidUser()方法代碼:

public isValidUser(): any { 
    const token = this.tokeStorageService.getTokenFromStorage(); 
    if (!token) { 
     console.log('cannot find token'); 
     return false; 
    } 

    const requestUrl = environment.gatewayUrl + environment.authorizationService + environment.userServiceEndPoint; 
    const headers = new Headers(); 
    headers.set('Authorization', 'Bearer ' + token); 
    const options = new RequestOptions({headers: headers}); 

    return this.http.get(requestUrl, options).catch(this.errorService.handleError); 
    } 

的這裏的想法是隻返回return this.http.get(requestUrl, options).catch(this.errorService.handleError);authService.isValidUser()代碼工作後。

我不認爲這是執行此類請求的正確方式,因爲我的第二個請求在第一個請求之前已經完成。

也許我錯過了如何正確使用它的一些方法?

謝謝。

+0

'因爲我的第一個請求已經完成之前,第二個'' - 這是你正在嘗試做什麼,不是嗎? – TheUnreal

+0

呃我的錯。第二個在第一個請求完成之前完成 –

+0

在您的代碼中,第一個在第二個之前完成...第一個請求的結果是「響應」。 – TheUnreal

回答

1

代碼在哪裏試圖鏈接這兩個函數?

你可以使用switchMap運算符來實現你想要的。這裏是docs

我想你需要的東西是這樣的:

isValidUser() 
    .filter(isValidUser => isValidUser) // <-- perhaps you need this filter since you want to make getCompany call only if user is valid 
    .switchMap(() => getCompany()) 
    .subscribe(...do something...); 

不要忘記添加import 'rxjs/add/operator/switchMap';。您也可以使用mergeMapflatMapmergeMapflatMap的synonim),但它不是優選的。

As @BeetleJuice在評論中提到:爲什麼switchMap更好?例如,您使用mergeMap或flatMap,並且導致另一個該代碼的調用。即使兩個第一個請求沒有完成,新的請求也會被髮送。第二批請求甚至有可能比第一批請求更快完成。之後,第一個包完成,你有你的狀態錯誤的數據。爲了解決這個RxJS提供了完美的運營商switchMap。如果你在上面的情況下使用了這個操作符,那麼第一個observable(第一個請求包)將被取消。只有最後一次觀察(來自上次調用)纔會保持活躍狀態​​。只有在有可能在短時間內多次運行該代碼時,才需要switchMap。如果您知道此代碼將只運行一次mergeMap/flatMap將爲您執行相同操作。

另外,請查看this post

+0

我沒有鏈碼。這是問題 –

+0

酷。那就是答案。 –

+3

Sharikov,@DenissM。 'switchMap'是比mergeMap更好的選擇,因爲在這個用例中,你希望保持執行的順序 - 第二個http請求只能在第一個請求解決後才能生成。 'mergeMap'允許多個第一類請求被緩衝的第二個請求通過線傳輸的可能性。 – BeetleJuice