2017-11-24 5 views
0

私はangular4を使用していますが、現在私はobservablesを使っていくつかのデータをフェッチするときにグローバルローダを作成する必要があります。私の考えは、ローダーhtmlを作成し、それをdomにレンダリングし、成功とエラーでそれをきれいにすることでした。どのようにAng4のサービスを使用してDOMにhtml要素を挿入するのですか?

は、どのように私は、サービスを利用して、私のローダHTMLをダンプすることができ、それはあなたがこれを行うには2つの方法がありグローバルローダー

//dump a loader html 
this.http.get('controller/nmethod').subscribe(success => { 
     //clear the loader html 
    }, error => { 
     //clear the loader html 
    },() => { 
     //clear the loader html 
    }) 
+3

で何もしない場合は、コンポーネントのフラグを設定し、それを使用することができます使用することができますtrueの場合はローダーを表示し、falseの場合はローダーを非表示にします。サンプルでは、​​ ngIf = "flag"をローダーに配置します。 –

+0

なぜ 'component'にローカル' subscribe'を使わず、 'ngBusy'ディレクティブを使ってください。 –

答えて

0

になります。

デモについて:

component.ts

export class AppComponent { 

    isDataLoaded: boolean = false 
    data: string = "" 

    constructor() { 
    this.loadData() 
    } 

    showResult() { 
    this.loadData() 
    } 

    private loadData() { 
    this.isDataLoaded = false 
    Observable.of("data is loaded") 
     .delay(1000) 
     .subscribe(
     succes => { 
      this.isDataLoaded = true 
      this.data = succes 
     }, 
     err => { 
      this.isDataLoaded = true 
      this.data = err 
     } 
    ) 
    } 
} 

が最初にフラグを持つことで、例えば、観察が成功またはエラーであるときに切り替えることをisDataLoaded

component.html

<div *ngIf="isDataLoaded; else loading"> 
    {{data}} 
</div> 
<ng-template #loading> 
    <p>Loading...</p> 
</ng-template> 

<button (click)="showResult()">Show result</button> 

それともそれが終了していますかどうかを確認するために、観察を使用します。

componet.ts

export class AppComponent { 

    data2$: Observable<string> 

    constructor() { 
    this.loadData2() 
    } 

    showResult() { 
    this.loadData2() 
    } 

    private loadData2() { 
    this.data2$ = Observable.of("data 2 is loaded").delay(3000) 
    } 
} 

component.html

<div *ngIf="data2$ | async; let data2; else loading2"> 
    {{data2}} 
</div> 
<ng-template #loading2> 
    <p>Loading...</p> 
</ng-template> 

<button (click)="showResult()">Show result</button> 

ここに完全なデモを:https://stackblitz.com/edit/angular-lv66zw?file=app%2Fapp.component.ts

最初のオプションは、あなたが他の人の行動をすれば、観察が

を終了したときに、第2のオプションは短く、あなたがコールバック

関連する問題