加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:31:22 所属栏目:安全 来源:网络整理
导读:我想创建服务,它可以与一个组件进行交互. 我的应用程序中的所有其他组件应该能够调用此服务,并且此服务应该与此组件交互. 如何从服务中调用组件方法? @Component({ selector:'component'})export class Component{ function2(){ // How call it? }} 从这个
我想创建服务,它可以与一个组件进行交互.
我的应用程序中的所有其他组件应该能够调用此服务,并且此服务应该与此组件交互.

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

@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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读