2017-07-26 38 views
1

我對angular 4很新,所以我需要在每次http請求完成時顯示spinner。 所以我有許多組件:Angular 4顯示每個http請求的加載gif

<component-one></component-one> 
<component-two></component-two> 
<component-three></component-three> 
<component-n></component-n> 

每個人心中都有一個http請求查詢和保存一些數據,以便當HPPT請求時我想表明我<loading></loading>組件,所以我想是不是一個好的做法注入我的用http請求將組件加載到每個其他組件中。我可以添加一個過濾器或角度的東西,允許我在每個有http請求的組件中自動加載<loading>組件?

此外,當http請求完成後,我想顯示一條消息,如「完成」或someting。

如果有人能爲我提供一個解決方案,我會非常感激,ty。

+2

[角2裝載機每個HTTP請求(的可能的複製https://stackoverflow.com/questions/38144655/angular-2-loader-on-each-http - 請求) – echonax

+1

檢查此[鏈接](https://rahulrsingh09.github.io/AngularConcepts/#/faq)它有問題和答案 –

回答

4

UPD:plunker。看看app.ts。對不起,所有內容都放在一個文件中。

在Angular 4.3中有一個支持攔截器的新HttpClientModule。其主要思想是有這樣的事情:

@Injectable() 
export class LoadingIndicatorService { 

    private _loading: boolean = false; 

    get loading(): boolean { 
     return this._loading; 
    } 

    onRequestStarted(): void { 
     this._loading = true; 
    } 

    onRequestFinished(): void { 
     this._loading = false; 
    } 
} 

然後你剛剛從申請克里斯托弗的回答邏輯您HttpInterceptor。

你應該知道的唯一的事情是同時請求。這可以通過例如爲每個請求生成唯一標識符並將其存儲在某個地方直到請求完成來解決。

然後你可以有一個全球LoadingIndicator組件注入LoadingIndicatorService

有關HttpClientModule詳情:https://medium.com/codingthesmartway-com-blog/angular-4-3-httpclient-accessing-rest-web-services-with-angular-2305b8fd654b

+0

也可以在4.2.2中使用嗎? – mcmwhfy

+0

只從4.3.0開始。那麼,這不是一個主要版本。它應該實際上向後兼容。 –

+0

只有當你開發了類似的東西,並且很容易讓你創建一個重擊者,而不是花費太多時間,你是否還有一個小例子? – mcmwhfy

1

http請求返回可以訂閱的Observable

例如,讓我們對用戶進行身份驗證。

在我的服務:

login(email: string, password: string): Observable<User> { 
    let url = this.authUrl + '/login'; 

    return this.http 
     .post(url, JSON.stringify({ email, password })) 
     .map(res => res.json()); 
} 

我打電話訂閱此方法在我的組件:

this.isLoading = true; 
this.authService.login(email, password) 
     .subscribe(data => { 
      this.isLoading = false; 
      // Do whatever you want once the user is logged in 
      // Where 'data' is the User returned by our http request 
     }, error => { 
      // Handle errors here 
     } 

注意試圖登錄我們的用戶之前設置爲true的布爾isLoading,並且一旦認證成功就爲假。

這意味着您可以顯示和這個布爾隱藏加載動畫,像這樣的:

<loading-component *ngIf="isLoading"></loading-component> 
0
component.ts

public loading: boolean = false; 

您component.html內

<div *ngIf="!loading"> 
    <component-one></component-one> 
    <component-two></component-two> 
    <component-three></component-three> 
    <component-n></component-n> 
</div> 

<loading *ngIf="loading"></loading> 

只要您需要查看加載圖標,只需設置this.loading = true;和掩蓋它this.loading = false;這將隱藏你不希望看到的,而裝載的部件和顯示加載圖標,而不是

+0

請給我完整的示例或代碼,我試過了你的方法不適合我 –