简体   繁体   中英

Angular: call function from other component

I'm trying to make two angular components and I want to call a function from the first component in the second component. When I try this I get following error message: Cannot red property 'functionName' of undefined . How can this be solved?

Here a link of an example: https://stackblitz.com/edit/angular-rre4gb

That's because the component you want to call its function, is not instantiated.

for component communication you can use a service instead:

Service

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

Component

in your component:

@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();
   }
}

As others have stated, I would prefer a shared service with a Subject among these components.

service :

@Injectable()
export class SharedService  {

  mySubject = new Subject();

}

WorldComponent (subscriber):

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

HelloComponent (publisher):

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

You can find the updated example here: https://stackblitz.com/edit/angular-rnvmkq?file=app%2Fworld.component.ts

The best way to share information between multiple components is generally through a service.

Create a separate file: file.service.ts

Provide the service in the app.module.ts file

Inject the service into each component. Then you'll have access to the variables in both components

See this: https://angular.io/tutorial/toh-pt4

错误的原因是,hello组件未导入,但您不应在其他组件之间调用服务,而应从其他组件调用组件,就像已经提出的其他答案一样。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM