【问题标题】:behaviourSubject in angular2 , how it works and how to use itangular 2 中的 behaviorSubject ,它是如何工作的以及如何使用它
【发布时间】:2016-07-24 02:32:47
【问题描述】:

我正在尝试构建如下共享服务

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() 等任何可用的都不是函数,所以有人可以向我展示它的实际工作原理以及在我搜索示例时如何实现它,但没有任何意义对我来说。

【问题讨论】:

    标签: angular rxjs angular2-changedetection


    【解决方案1】:

    简化为一个属性,它应该看起来像这样。我将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); 
        });
      }
    }
    

    【讨论】:

    • 以及如何检索它的价值? console.log('behiob' + shared.space.single());
    • 不应该是space: BehaviorSubject&lt;string&gt;而不是`Subject
    • 这不是本意。 BehaviorSubject is-a Subject AFAIK。
    猜你喜欢
    • 2018-02-10
    • 2015-04-04
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多