2016-08-23 69 views
0

問題:組件的依賴和使用的生命週期掛鉤的邏輯

<div class="appContainer"> 
    <my-cube-container></my-cube-container> 
    <my-toolbox></my-toolbox> 
    </div> 

my-toolbox調用它的構造函數中的服務。 service A調用另一個service B並將值設置爲該服務。 my-cube-container在其構造函數中調用service B。當my-cube-container調用service B時,值不會被初始化。

可能的解決方案:

  • 使用生命週期掛鉤:如果一個服務onNgInit()被調用時,它將是在組件構造函數中使用的任何其他服務後調用。然而,這感覺有點不對,並且不明確。
  • 告訴組件與另一組件相關的角度。我認爲這更明確,我想這樣做。

回答

1

你有幾個選擇,保持它們的方式,但將所有調用到你的服務到ngInit()所有的邏輯應該在該方法內,而不是在構造函數。當涉及到測試時,這會讓你的生活更加艱難。之後,您可以創建service B上的值的可觀察值,並使您的<my-cube-container></my-cube-container>訂閱該可觀察值,以便在這些值可用時獲得通知。

另一種選擇是創建一個新組件來包裝這兩個組件。因此,這部分負責將數據饋送到<my-cube-container><my-toolbox>,並會是這個樣子:

<my-wrapper> 
    <my-cube-container [values]="serviceBValues"></my-cube-container> 
    <my-toolbox (setValues)="setValues($event)"></my-toolbox> 
</my-wrapper> 

而且ts代碼將是這樣的:

import {Component} from 'angular2/core'; 

@Component({ 
    selector: 'my-wrapper', 
    template: ` 
    <my-wrapper> 
     <my-cube-container [values]="serviceBValues"></my-cube-container> 
     <my-toolbox (setValues)="setValues($event)"></my-toolbox> 
    </my-wrapper> 
    ` 
}) 
export class MyWrapperComponent { 
    public serviceBValues; 

    constructor(private serviceA: ServiceB, private serviceB: ServiceB) 

    setValues(event) { 
    console.log(event); 
    this.serviceA(event); 
    this.serviceBValues = this.serviceB.getValues(); // I guess they will be available by now, if not use promises or observables 
    } 
} 

所以<my-wrapper>將負責對於所有的邏輯和你的實際組件將是更多的虛擬組件,只顯示你的數據。

+0

很好的答案,但我不得不不同意。這是爲什麼。對於觀察者設計,這意味着樹中的每個組件都將在訂閱回調被調用之前被初始化。這意味着my-cube-container及其子節點中的初始化往往是第一次,這實際上並不值錢。第一次往返也可能產生錯誤,因爲my-cube-container將具有未初始化的值(除非我有默認值) 。我希望少一些「哈克」 – Ced

+0

其實這是我的問題的解決方案。我仍然認爲這並不完美 – Ced