2017-09-11 26 views
1

我使用ngx-loading並希望能夠觸發它從兒童組件中顯示/隱藏。以下是我目前有:ngx-loading從另一個組件切換

App.Component

import { Component, Injectable } from '@angular/core'; 

@Injectable() 
export class AppComponent implements OnInit{ 
    public loading = false; 

    constructor() { } 

    loader() { 
    this.loading = !this.loading; 
    console.log(this.loading); 
    } 
} 

輔元件

import { AppComponent} from '../app/app-component'; 
import { MyService } from '../service/my-service'; 

@Component({ 
    selector:'child-component', 
    templateUrl: './child.component.html', 
    providers: [AppComponent, MyService] 
}) 

export class ChildComponent implments OnInit { 
    constructor(private loader: AppComponent, private service: MyService) {} 

    ngOnInit(): void { 
    this.getData(); 
    } 


    getData() { 
    this.loader.loader(); 
    this.service.getDataFromService().then(res => { 
     this.myModel = res; 
     this.loader.loader(); 
    } 
    } 
} 

如果我檢查我的日誌this.loader是切換從真到假,但ngx-loading組件不是。如果我在app.component ngx-loading顯示中設置加載的初始值,但不會隱藏。所以我知道裝載機正在工作。

任何想法?

回答

1

原因是更改檢測不運行。我創建了Plunker以使其工作。我建議你使用EventEmmiter(輸出)。主要思想是在承諾完成後,運行setTimeout來觸發changeDetection。

this.getData().then(() => {   
    setTimeout(() => { 
     this.load.emit() 
    }) 
+1

謝謝@alexKhymenko – jpdesigning

+0

不客氣! – alexKhymenko

相關問題