【发布时间】:2019-04-17 01:36:11
【问题描述】:
我有 2 个组件需要通信,中间有一个服务。
服务
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class CommunicationService {
// Observable string sources
private onOpen = new Subject<any>();
// Observable string streams
onOpen = this.onOpen.asObservable();
// Service message commands
callComponentMethod() {
this.onOpen.next();
}
}
组件 A
import { Component } from '@angular/core';
import { CommunicationService } from './communication.service.ts'
@Component({
selector: 'app-comp1',
template: `
<button type="button" (click)="callMethod()">Call method from Component1</button>
`
})
export class Component1 {
constructor( private communicationService: CommunicationService ) { }
callMethod = function () {
this.communicationService.onOpen();
}
}
组件 B
import { Component } from '@angular/core';
import { CommunicationService } from './communication.service.ts'
@Component({
selector: 'app-comp2',
template: ``
})
export class Component2 {
constructor( private communicationService: CommunicationService ) {
this.communicationService.onOpen.subscribe(
() => {
alert('(Component2) onOpen');
}
);
}
}
在这个 plunker 之后:http://plnkr.co/edit/SmntWy0GTNdvGB5Jb3hO?p=preview 调用了该方法,但是我想传递一个参数。我该怎么做呢 ?
【问题讨论】:
-
也许你可以在流中传递参数:callComponentMethod(params) { this.onOpen.next(params); }
-
你想传递哪个参数?
-
取决于哪里,现在我希望有一个自定义类型的对象
标签: angular observable