angular2中的behaviourSubject,它如何工作以及如何使用 [英] behaviourSubject in angular2 , how it works and how to use it

查看:447
本文介绍了angular2中的behaviourSubject,它如何工作以及如何使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照以下步骤构建共享服务

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中的behaviourSubject,它如何工作以及如何使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆