Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

angular - behaviourSubject in angular2 , how it works and how to use it

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;
}

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());

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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); 
    });
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...