2017-04-21 30 views
2

我傳遞數據到一個可訪問的子組件,我可以使用這些數據構建出我的視圖。但是,我需要訪問@Input對象上的一個屬性來查找具有相同值的數組中的項目。相當簡單直接。當組件加載時,我在構造函數中執行此操作,以便立即可用。@Input()屬性無法訪問,因爲它說的對象在未定義的角2

但是,@Input對象回來undefined所以我不能訪問屬性。有人可以看看並告訴我這裏發生了什麼?

回到未定義的對象是「this.ConfirmOrderData」,就像我說的,我可以做ngFor重複這個對象屬性數組等,所以我很難爲什麼它是未定義的。

CODE:

@Input() ConfirmOrderData:{ 
    orderRefillData: Array<any>, 
    selectedUser: any, 
    DeliveryTypeId: any, 
    PickupLocationId: any, 
    PaymentTypeId: any, 
    AddressType: any 
}; 

constructor(
fb: FormBuilder, 
public refillService: refillService, 
public globalService: globalService 
) { 
    this.userInfo = this.globalService.getUserInfo(); 
    this.deliveryAddress = this.userInfo.userInfo.StreetAddresses.find((item) => item.DeliveryTypeId == this.ConfirmOrderData.AddressType.AddressTypeId) 
    //the this.ConfirmOrderData object in the above line comes back undefined. Don't know why. 
} 
+0

當您直接使用屬性在模板中,就像沒有被觀察到的數據一樣,它必須被定義,或者你可以使用?像'data?.item?.couldbelate' – Dylan

回答

2

這是因爲你試圖在執行操作來分配空值後,你應該實例化屬性@Input在構造函數中。在執行構造函數中的動作時,輸入值尚未設置。您需要將此邏輯轉移到ngOnInit,使值被設置,也看到這一點:Difference between Constructor and ngOnInit

所以你的邏輯移動到OnInit,它應該是不錯的:)

ngOnInit() { 
    this.userInfo = this.globalService.getUserInfo(); 
    this.deliveryAddress = this.userInfo.userInfo.StreetAddresses.find((item) => 
     item.DeliveryTypeId == this.ConfirmOrderData.AddressType.AddressTypeId) 
} 
+0

你有沒有嘗試過任何一個答案,有幫助還是需要進一步的幫助? :) – Alex

+1

我實際上在父組件中執行此操作,並將其包含在傳遞給子對象的數據對象中,所以它已經可用並以我需要的方式存儲在變量中,但是您的方式肯定更靈活,而且我將使用它向前移動(或當我重構這件作品時)。謝謝。 –

0

創建一個模型

export interface ConfirmOrderData:{ 
    orderRefillData: Array<any>, 
    selectedUser: any, 
    DeliveryTypeId: any, 
    PickupLocationId: any, 
    PaymentTypeId: any, 
    AddressType: any 
}; 

用它在你的組件作爲

@Input() confirmOrderData :Array<ConfirmOrderData>; 

爲了避免您需要實例作爲

未定義的問題

在你定義

@Input() confirmOrderData :Array<ConfirmOrderData>= new Array<ConfirmOrderData>(); 

或您的構造函數中的

constructor(...){ 
    this.confirmOrderData = new Array<ConfirmOrderData>(); 
} 

當你做如上,你會在orderRefillData爲未定義越來越另一個錯誤。要修復它你的對象實例化作爲

this.confirmOrderData.orderRefillData = new Array<any>(); 

一個簡單的修復,對所有屬性

this.confirmOrderData ={ 
     orderRefillData:new Array<any>(), 
     selectedUser: '', 
     DeliveryTypeId: '', 
     PickupLocationId: '', 
     PaymentTypeId: '', 
     AddressType: '' 
} 
相關問題