Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

angular - How to call component method from service? (angular2)

I want to create service, which can interact with one component. All another components in my app, should be able to call this service, and this service should interact with this component.

How to call component method from service?

@Component({
  selector:'component'
})
export class Component{

  function2(){ 
    // How call it?
  }
}

From this servive?

@Injectable()

export class Service {


  callComponentsMethod() {
    //From this place?;
      }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Interaction between components can be indeed achieved using services. You will need to inject the service use for inter-component communication into all the components which will need to use it (all the caller components and the callee method) and make use of the properties of Observables.

The shared service can look something like this:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class CommunicationService {

  // Observable string sources
  private componentMethodCallSource = new Subject<any>();
  
  // Observable string streams
  componentMethodCalled$ = this.componentMethodCallSource.asObservable();

  // Service message commands
  callComponentMethod() {
    this.componentMethodCallSource.next();
  }
}

Example:

Sender:

callMethod = function () {
   this.communicationService.callComponentMethod();
}

Receiver:

this.communicationService.componentMethodCalled$.subscribe(() => {
      alert('(Component2) Method called!');
});

I have created a basic example here, where clicking on a button from Component1 will call a method from Component2.

If you want to read more on the subject, please refer to the dedicated documentation section: https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...