【问题标题】:Angular: call function from other componentAngular:从其他组件调用函数
【发布时间】:2018-01-22 04:22:33
【问题描述】:

我正在尝试制作两个角度组件,并且我想从第二个组件中的第一个组件调用一个函数。当我尝试这个时,我收到以下错误消息:Cannot red property 'functionName' of undefined。怎么解决?

这里是一个例子的链接:https://stackblitz.com/edit/angular-rre4gb

【问题讨论】:

  • 快速入门,请查看我更新的答案。

标签: javascript angular typescript


【解决方案1】:

那是因为你要调用它的函数的组件没有被实例化。

对于组件通信,您可以改用service

服务

@Injectable()
export class MyService {
    myCustomFunction(){
    }
}

组件

在您的组件中:

@Component({
   selector: 'my-component',
   providers: [ MyService ]
})
export class MyComponent {

   // inject your service to make it available
   constructor(private service: MyService){}

   doStuff(){

      // call function which is located in your service
      this.service.myCustomFunction();
   }
}

【讨论】:

    【解决方案2】:

    正如其他人所说,我更喜欢这些组件中带有Subject 的共享服务。

    服务

    @Injectable()
    export class SharedService  {
    
      mySubject = new Subject();
    
    }
    

    WorldComponent(订阅者):

    export class WorldComponent  {
      constructor(private sharedService: SharedService){
        this.sharedService.mySubject.subscribe((data)=>{
          this.worldFunction();
        })
      }
    

    HelloComponent(发布者):

    public helloFunction() {
        alert('Hello');
        this.sharedService.mySubject.next(true);
      }
    

    您可以在此处找到更新后的示例:https://stackblitz.com/edit/angular-rnvmkq?file=app%2Fworld.component.ts

    【讨论】:

      【解决方案3】:

      错误的原因是 hello 组件没有被导入,而不是从另一个组件调用一个组件,你应该在两者之间使用一个服务,正如其他答案已经建议的那样。

      【讨论】:

        【解决方案4】:

        在多个组件之间共享信息的最佳方式通常是通过服务。

        创建一个单独的文件:file.service.ts

        在 app.module.ts 文件中提供服务

        将服务注入到每个组件中。然后你就可以访问两个组件中的变量了

        看到这个:https://angular.io/tutorial/toh-pt4

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-03-06
          • 2017-06-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-05
          • 1970-01-01
          • 2013-07-20
          相关资源
          最近更新 更多