简体   繁体   中英

Calling component from service - angular

I already tried a few approaches but none of them seems to work so far. I am trying to call a function in one component on click event in another component. I don't have any errors in the console.

First component

constructor(public projectService: ProjectOverviewService) {  }
delete(event) {
    this.projectService.onFirstComponentButtonClick(); 
}

Service

invokeFirstComponentFunction = new EventEmitter();
subsVar: Subscription;

onFirstComponentButtonClick() {
    this.invokeFirstComponentFunction.emit();
} 

Second component

constructor(public projectOverviewService: ProjectOverviewService){}
ngOnInit(): void {
if (this.projectOverviewService.subsVar == undefined) {
      this.projectOverviewService.subsVar = this.projectOverviewService.
        invokeFirstComponentFunction.subscribe((name: string) => {
          console.log("I am here!!!");
        });
    }
}

I am not hitting console.log ever.

You can use RXJS import Subject

First component

constructor(public projectService: ProjectOverviewService) {  }

delete(event) {
  this.projectService.invokeFirstComponentFunction.next(); 
}

Service

 public invokeFirstComponentFunction = new Subject();

Second Component

subsVar: Subscription;


constructor(public projectOverviewService: ProjectOverviewService){}
ngOnInit(): void {
      this.subsVar = this.projectOverviewService.invokeFirstComponentFunction.
       .subscribe(() => {
          console.log("I am here!!!");
        });
}
ngOnDestroy(){
this.subsVar && this.subsVar.unsbscribe()
}

If you are planning to establish communication between 2 components using a service, then event-emitter is not the approach. This is what I would do:

First component

constructor(public projectService: ProjectOverviewService) {  }
delete(event) {
    this.projectService.onFirstComponentButtonClick("Name"); 
}

Service

invokeFirstComponentFunction = new Subject<string>();
subs$ = this.invokeFirstComponentFunction.asObservable();

onFirstComponentButtonClick(name: string) {
    this.invokeFirstComponentFunction.next(name);
} 

Second component

constructor(public projectOverviewService: ProjectOverviewService){}
    
ngOnInit(): void {
  this.projectOverviewService.subs$.subscribe((name: string) => {
    console.log("I am here!!!");
  });
}

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