簡體   English   中英

角度:從其他組件調用函數

[英]Angular: call function from other component

我正在嘗試制作兩個角度組件,並且想從第二個組件的第一個組件調用一個函數。 當我嘗試此操作時,出現以下錯誤消息: Cannot red property 'functionName' of undefined 如何解決呢?

這里是示例的鏈接: https : //stackblitz.com/edit/angular-rre4gb

這是因為您要調用其功能的組件未實例化。

對於組件通信,可以改為使用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();
   }
}

正如其他人所說,在這些組件中,我希望與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

在多個組件之間共享信息的最佳方法通常是通過服務。

創建一個單獨的文件:file.service.ts

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

將服務注入每個組件。 然后,您將可以訪問兩個組件中的變量

看到這個: https : //angular.io/tutorial/toh-pt4

錯誤的原因是,hello組件未導入,但您不應在其他組件之間調用服務,而應從其他組件調用組件,就像已經提出的其他答案一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM