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.
In Angular services, I would use BehaviorSubject for a data service as an angular service often initializes before component and behavior subject ensures that the component consuming the service receives the last updated data even if there are no new updates since the component's subscription to this data.
BehaviorSubject is a variant of a Subject which has a notion of the current value that it stores and emits to all new subscriptions. This current value is either the item most recently emitted by the source observable or a seed/default value if none has yet been emitted.
1. First create a BehaviorSubject in order service which holds the initial state of order count ,so that it can be used by any component. 2. Now all observers(3 components) need to subscribe to source observable to get current value and show it on UI.
Observable is a Generic, and BehaviorSubject is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities. An observable can be created from both Subject and BehaviorSubject using subject.
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);
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With