2017-10-16 26 views
0

我是重構代碼,它在2個組件之間有很多重複的方法。組件A是組件B的子組件,它們都可以是不同的實例,實際上它們應該是。我的問題是,在我發佈數據的一些方法中,當我在將方法傳遞給服務之後嘗試獲取輸入時,我無法將模板傳遞給不知道爲什麼。使用共享服務處理輸入和輸出

我有這樣的事情在此刻:

A成分和B的發射活動和,因爲我不能在邏輯分離開來,我沒有改變這些方法,我怎麼能做出改變輸入服務端並獲取組件上的更改?有什麼幫助嗎?

component A 

export class CompA{ 
template: ... 
... 
inputs [ 
    'value1' 
    'value2' 
] 
outputs: [ 
'doSomething' 
'doSomething2' 
'doSomething3' 
] 

public value1: string; 
public value2: string 

addLine(){ 
//simple example 
    if(this.value1 == ""){ 
    this.doSomething1.emit(3) 

    // the functions are obviously bigger but i need this emit inside the service and catch the event in the component 
    } 
} 
+1

你能改述這個問題,也許增加一些代碼嗎?真的很難理解你在問什麼。 – zfrisch

+0

基本上我需要知道如何通過一些輸入這種方式服務 - > componentA,如果我傳遞邏輯到服務輸入,我需要在組件中的服務要麼,我怎麼能得到的數據,例如我試圖在ngOnInit中初始化數據,但它不聽更改 –

回答

0

我不確定我是否理解這個問題。也許建立一個能夠證明這個問題的搗蛋者會在這裏很有幫助。

一般來說,如果您需要更新服務中的數據,只需設置值即可。

例如:

服務

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

@Injectable() 
export class ShareService { 
    public data: string; 

    setData(newdata : string){ 
     this.data = newdata; 
    } 

    clearData(){ 
     this.data = ''; 
    } 
} 

組件,其設定值

export class PageA { 
    constructor(private shareService: ShareService, private router: Router){ 
    } 
    gotoPageB(){ 
     this.shareService.setData("Sample data"); 
     this.router.navigate(['pageb']); 
    } 

} 

的組件,得到值

export class PageB { 
    constructor(private shareService: ShareService){ } 

    get somedata() : string { 
     return this.shareService.data; 
    } 
} 

這裏的關鍵是在獲取值的組件中使用getter屬性(在本例中爲PageB),以便在數據服務值發生更改時隨時更新。

這完全接近你所問的嗎?