【问题标题】:emit() property of undefined - EventEmitter / @Output issue未定义的 emit() 属性 - EventEmitter / @Output 问题
【发布时间】:2017-10-19 22:44:35
【问题描述】:

我有一个父组件和一个子组件。我已经在父母与孩子之间建立了联系,但似乎缺少从孩子到父母的另一个方向的细节,我认为这是我的无知,因为 angular4/typescript 对我来说都是新的。

所以父组件承载一个子组件,并将数据传给子组件就好了;

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

&lt;app-component-name&gt; 恰好是一个对话框子组件,其意图是用户输入一个字符串地址,我通过谷歌地图 API 将其地理编码为 Lat/Lng。对话框显示正常,输入输入并返回正常,地理编码通过并且我的纬度/经度返回没有问题....我的问题是将带有坐标等的对象返回到地图所在的父组件所以我可以为它添加一个标记等等......

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

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

然后应该将这个 bug 发送回父组件的方法(它触发得很好,因为它也是我从 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 返回的对象,看起来不错,谷歌地图返回我的坐标和数据,如图所示。所以我希望你们中的一个人能在更长的时间内发现我的愚蠢行为,为什么我会得到那个未定义的emit 属性?我只是做了一些菜鸟,比如忘记定义一些东西吗?

我知道我试图发出的所有值都在那里,所以我显然缺少一些基本定义或其他东西,对吗?谢谢亲手学习。

【问题讨论】:

  • 你在哪里调用这个addNewSomething 在你的子组件中。您可以查看this 以获得简单的事件发射器
  • @RahulSingh 该方法从子 component.html 中的表单中调用,例如; &lt;form name="newLoc" (ngSubmit)="addNewSomething(newLoc)"...... 其中 newLoc 是 ngForm 对象 - 我会去看看你提供的链接,看看我是否找不到明显的东西谢谢:)
  • 所有属性都未定义还是只有一个?
  • @RahulSingh Nah 所有属性都应该没问题,因为我使用相同的属性在子组件中执行其他操作并且它们很好。我似乎无法将该对象返回给父级,因此我可以将其推送到父组件上的标记数组。
  • @gyc 是的,进口在那里,intellij 擅长抱怨这类事情。还尝试了备用发射器语法,但仍然得到相同的Cannot read property 'emit' of undefined 错误。

标签: angular google-maps typescript


【解决方案1】:

所以问题出在嵌套方法提供的变量范围内。对于其他读者来说,这是伪修复。

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; 是修复。感谢所有试图提供帮助的人。 :)

【讨论】:

    猜你喜欢
    • 2021-06-27
    • 2020-10-09
    • 1970-01-01
    • 2021-02-22
    • 2021-06-19
    • 2019-01-25
    • 2019-06-27
    • 1970-01-01
    • 2014-12-12
    相关资源
    最近更新 更多