我有2个需要通信的组件,中间是一个服务。
服务
responseJSON
组件A
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();
}
}
组件B
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();
}
}
下面是这个http://plnkr.co/edit/SmntWy0GTNdvGB5Jb3hO?p=preview,该方法被调用,但是,我想传递一个参数。我该怎么做呢 ?
答案 0 :(得分:1)
您的实现中有很多不正确的地方。这是您要实现的目标的工作示例:
您不需要使用Subject
,您可以使用常规的可观察对象,然后将新值“推送”到该可观察对象的发射器:
export class CommunicationService {
// Observable string sources
private emitter: any;
public messageInbox: Observable<any>
constructor(){
this.messageInbox = Observable.create(e => this.emitter = e);
}
// Service message commands
public SendMessage() {
this.emitter.next("hello");
}
您的组件中的代码基本上没问题。
答案 1 :(得分:1)
调用$Query = Database::Prepare("SELECT * FROM new_jobs WHERE thickness LIKE ?");
$Query->Execute(array("%".$thickness."%"));
类的callComponentMethod
函数,而不是调用CommunicationService
。其次,如果要传递信息,可以通过将值传递给onOpen
函数来实现。
下面是修改后的代码
callComponentMethod
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(info:any) {
this.onOpen.next(info); //<-- pass the value to subscribers
}
}