我正在尝试按照以下方式构建共享服务
import {Injectable,EventEmitter} from 'angular2/core';
import {Subject} from 'rxjs/Subject';
import {BehaviorSubject} from 'rxjs/subject/BehaviorSubject';
@Injectable()
export class SearchService {
public country = new Subject<SharedService>();
public space: Subject<SharedService> = new BehaviorSubject<SharedService>(null);
searchTextStream$ = this.country.asObservable();
broadcastTextChange(text: SharedService) {
this.space.next(text);
this.country.next(text);
}
}
export class SharedService {
country: string;
state: string;
city: string;
street: string;
}
我不知道如何实现BehaviourSubject基本上我在这里尝试的只是一团糟我猜我在使用
在子组件中调用此值console.log('behiob' + shared.space.single());
抛出一个错误.single()/ last()等等什么是可用的不是一个函数所以有人可以告诉我它是如何工作的以及如何实现它,因为我搜索了这些例子但没有任何意义对我来说。
答案 0 :(得分:20)
减少到一个属性应该是这样的。我将SharedService
更改为string
,因为对我来说使用名为XxxService
的类型作为事件值没有意义:
import {Injectable} from 'angular2/core';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
@Injectable()
export class SearchService {
public space: Subject<string> = new BehaviorSubject<string>(null);
broadcastTextChange(text:string) {
this.space.next(text);
}
}
@Component({
selector: 'some-component'
providers: [SearchService], // only add it to one common parent if you want a shared instance
template: `some-component`)}
export class SomeComponent {
constructor(searchService: SearchService) {
searchService.space.subscribe((val) => {
console.log(val);
});
}
}