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

查看:104
本文介绍了如何从服务中调用组件方法? (角度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/docs/ts/latest/cookbook/component-communication.html#!#双向服务

If you want to read more on the subject, please refer to the dedicated documentation section: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

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

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