2017-10-16 96 views
1

我有一個帶有子組件的父組件。我有父母之間的約束確定,但似乎缺少一個細節從孩子到父母的其他方向,我認爲是我的無知,因爲angular4/typescript對我來說都是新手。未定義的emit()屬性 - EventEmitter/@Output問題

因此,父組件託管一個子組件並將數據傳遞給子罰款;

<app-component-name (onSomethingAdded)="doSomethingWithIt($event)"></app-component-name> 

<app-component-name>恰好是與用戶輸入的,我通過谷歌地圖API地理編碼到緯度/經度字符串地址的意圖對話框子組件。對話框顯示正常,輸入輸入並返回正常,地理編碼通過,我的經緯度返回沒有問題....我的問題是獲取該對象與座標等回到父組件地圖是所以我可以爲它添加一個標記等...

在子組件中,我像這樣聲明瞭@Output;

@Output() 
onSomethingAdded = new EventEmitter<{animation:any, title: string, position: {lat:number, lng:number}}>(); 

那麼這是應該發出這樣開溜回父組件(火災很好,因爲它也是在那裏我做從對話框子組件的輸入地址解析)方法看起來像這樣...

addNewSomething(newLoc) { 

    // A bunch of other stuff omitted for the sake of a small example 
    // THIS BUGGER below pukes at me 
    // Uncaught TypeError: Cannot read property 'emit' of undefined 

     this.onSomethingAdded.emit({ 
      animation: google.maps.Animation.DROP, 
      title: newLoc.form.controls.title.value, 
      position: { 
      lat: res[0].geometry.location.lat(), 
      lng: res[0].geometry.location.lng() 
      } 
     }); 
} 

哪裏newLoc是我從ngForm回來從對話框中輸入的對象,看起來不錯,和谷歌地圖返回我我COORDS和數據就好如圖所示爲緯度/經度。所以我希望你們中的一個人在這個時間內能夠真正快速地發現我的愚蠢,爲什麼我得到那個未定義的emit屬性?我只是做一些喜歡忘記定義某些東西的東西嗎?

我知道我試圖發出的所有值都在那裏,所以我明顯缺少一些基本定義或其他東西?感謝您的學習。

+1

你在哪裏調用這個'addNewSomething'在你的子組件中。你可以看看[this](https://rahulrsingh09.github.io/AngularConcepts/event),以獲得一個簡單的事件發射器。 –

+0

@RahulSingh該方法從子component.html中的表單調用,如: '

+0

是所有的屬性未定義或只有一個? –

回答

0

所以問題原來是由嵌套方法提供的變量範圍。對於其他讀者來說,這是僞造的修復。

addNewSomething(newLoc) { 

    const that = this; 

    aChildMethod() { 


     yetAnotherNestedMethod() { 

     that.onSomethingAdded.emit({ 
      animation: google.maps.Animation.DROP, 
      title: newLoc.form.controls.title.value, 
      position: { 
      lat: res[0].geometry.location.lat(), 
      lng: res[0].geometry.location.lng() 
      } 
     }); 
     } 
    } 
}; 

其中that=this;是修復。感謝所有想要幫助的人。 :)