问题描述
我正在尝试按照以下方式构建共享服务
I am trying to build a shared service as follow
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 基本上我在这里尝试的只是一团糟,我猜我正在使用子组件调用这个值
I don't know how to implement BehaviourSubject basically what I am trying here is just a mess I guess and I am calling this value in child component by using
console.log('behiob' + shared.space.single());
抛出错误为 .single()/last() 等任何可用的都不是函数,所以有人可以告诉我它是如何工作的以及如何在我搜索示例时实现它,但没有任何意义给我.
which is throwing an error as .single()/last() etc whatever is available is not a function so can someone show me how it actually works and how to implement it as I searched for the examples but none is making sense to me.
推荐答案
减少到一个属性,它应该是这样的.我将 SharedService
更改为 string
因为对我来说使用名为 XxxService
的类型作为事件值没有意义:
Reduced to one property it should look like this. I changed SharedService
to string
because it doesn't make sense to me to use a type named XxxService
for an event value:
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);
});
}
}
这篇关于angular2 中的行为主题,它是如何工作的以及如何使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!