2016-02-13 76 views
1

我是新來Angular2,並開始了寫一個應用程序,所有的方法都在main.ts,進而該文件中引用其觀點的main.html。我將這個應用程序重構爲子組件和服務。所以,我現在有:Angular2更新模板從服務

- app.component.ts 
- app.html 
- sub.component.ts 
- sub.html 
- data.service.ts 

sub.component被包括在一個app.component指令。 app.compontent注入data.service,我可以調用從單擊事件服務app.component

問題

以前,我可以更新來自於組件的功能視圖中的進度條。現在,該功能是在其自己的服務,如何更新在服務的長期運行(遞歸)方法的進步的用戶?我想我必須要通過從服務到app.componentsub.component的進展,但如何打算做什麼?

回答

5

您可以使用EventEmitter將值傳遞給組件。在您的服務中創建發射器並在組件中訂閱它。

// data.service.ts 
class DataService() { 
    progress = new EventEmitter(); 

    longRunningMethod() { 
    this.progress.emit(value); 
    } 
} 

// app.component.ts 
class AppComponent() { 
    constructor(service: DataService) { 
    service.progress.subscribe(value => console.log(value)); 
    } 
} 
0

您需要訂閱來自組件服務(或兩個部件)。

您可以在引導提供服務(這將提供給所有組件)

bootstrap(App, [YourService]); 

還是要與組件提供它提供:

@Component({selector: "cmp", provide: [YourService]}) 

就以這個例子來看看: https://plnkr.co/edit/d4jIDQ4lSuXUDttKFAS6?p=preview

+0

這也適用!對不起 - 只能接受一個答案... – Fiona

+0

當然,沒問題。請注意一件事情:如果您在應用程序引導中提供服務 - 在您訂閱的所有組件中它與該類的相同對象。如果您爲每個組件提供它,則每次都創建一個新對象。 –