angular - 如何从服务中调用组件方法? ( Angular 2)

标签 angular typescript angular2-services angular2-components angular2-injection

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

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

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

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

从这个服务?

@Injectable()

export class Service {


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

最佳答案

组件之间的交互确实可以使用服务来实现。您需要将用于组件间通信的服务注入(inject)所有需要使用它的组件(所有调用者组件和被调用者方法),并利用 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();
  }
}

例子:

发件人:

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

接收方:

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

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

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

关于angular - 如何从服务中调用组件方法? ( Angular 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40788458/

相关文章:

angular - 从 ngx-image-cropper 返回文件以上传 - Angular

angular - 如果没有找到数据,如何在数据表 Angular Material 中显示空消息

angular - 如何让 RxJS observable 管道访问原始 observable 的发射和管道之前的发射?

选择的 Angular 6 默认值未在 Reactive Form 中被选中

Angular 2 "No provider for String!"

Angular 4 _ 如何动态更改谷歌地图 api key

javascript - 内部 html 在 DOM 树中完全渲染后会触发哪个事件?

typescript - 添加类型作为对象的键

HTTP : Detect changes in child component when update/save/delete

Angular 2在服务中获取routeParams