2016-04-04 19 views
12

Sto cercando di costruire un servizio condiviso da seguirebehaviourSubject in angular2, come funziona e come usarlo

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

non so come implementare BehaviourSubject fondamentalmente quello che sto cercando qui è solo un pasticcio Credo e mi sto chiamando questo valore nella componente figlio utilizzando

console.log('behiob' + shared.space.single()); 

che sta gettando un errore come .single()/ultima() ecc tutto ciò che è a disposizione non è una funzione così qualcuno mi può mostrare come funziona davvero e come implementarlo mentre cercavo gli esempi, ma nessuno ha senso per me.

risposta

19

Ridotto a una proprietà dovrebbe assomigliare a questo. Ho cambiato SharedService-string, perché non ha senso per me di utilizzare un tipo di nome XxxService per un valore di evento:

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

e come retrive il valore di esso ?? 'console.log ('behiob' + shared.space.single());' – Ironsun

+0

Ho aggiornato la mia risposta. –

+0

potresti aver risposto solo alla domanda precedente .... comunque grazie mille: d – Ironsun

Problemi correlati