我想创建可以与一个组件交互的服务。 我的应用程序中的所有其他组件都应该能够调用此服务,并且此服务应该与此组件交互。
如何从服务中调用组件方法?
@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/