微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从服务中调用组件方法? (angular2)

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

如何从服务中调用组件方法

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

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

从这个服务?

@Injectable()

export class Service {


  callComponentsMethod() {
    //From this place?;
      }
}
使用服务确实可以实现组件之间的交互.您需要将用于组件间通信的服务用途注入需要使用它的所有组件(所有调用程序组件和被调用方法)并使用Observables的属性.

共享服务可能如下所示:

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

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

如果您想了解有关该主题的更多信息,请参阅专用文档部分:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

原文地址:https://www.jb51.cc/angularjs/142256.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐