emitn的emit()属性 - EventEmitter / @Output issue

时间:2017-10-16 05:33:22

标签: angular google-maps typescript

我有一个带有子组件的父组件。我父母和孩子之间的约束确定,但似乎错过了从孩子到父母的另一个方向的细节,我认为这是我的无知,因为angular4 / typescript对我来说都是新的。

因此父组件托管子组件并将数据传递给子项;

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

<app-component-name>碰巧是一个对话框子组件,其意图是用户输入一个字符串地址,我通过google maps API对Lat / Lng进行地理编码。对话框显示正常,输入输入并返回正常,地理编码通过,我的lat / lng返回没有问题....我的问题是将coords等对象返回到父组件,其中地图是所以我可以为它添加标记等......

在子组件中,我声明我的@Ouput是这样的;

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

那么应该将这个bugger发送回父组件的方法(因为它也是我从Dialog子组件中的输入进行地理编码的地方,它会触发),看起来像这样......

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返回的对象并且看起来很好,并且谷歌地图会返回我的坐标和数据,如图所示,对于lat / lng来说很好。因此,我希望你们其中一个人能够更快地发现我对我的愚蠢,以及为什么我得到那个未定义的emit财产?我只是做了一些像忘记定义的东西吗?

我知道我想要发出的所有值都在那里,所以我显然缺少一些基本的定义或正确的东西?感谢您的学习。

1 个答案:

答案 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;是修复。感谢所有想要帮助的人。 :)