如何从服务调用组件方法?(角度2) [英] How to call component method from service? (angular2)

查看:23
本文介绍了如何从服务调用组件方法?(角度2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个可以与一个组件交互的服务.我的应用程序中的所有其他组件都应该能够调用此服务,并且此服务应与此组件交互.

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?
  }
}

来自这个服务?

@Injectable()

export class Service {


  callComponentsMethod() {
    //From this place?;
      }
}

推荐答案

组件之间的交互确实可以通过服务来实现.您需要将用于组件间通信的服务注入到所有需要使用它的组件(所有调用者组件和被调用者方法)中,并利用 Observables 的属性.

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

示例:

发件人:

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

接收方:

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

我在此处创建了一个基本示例,其中单击 Component1 中的按钮将从 Component2 调用一个方法.

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

如果您想阅读有关该主题的更多信息,请参阅专用文档部分:https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

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

这篇关于如何从服务调用组件方法?(角度2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆