2016-04-04 43 views
12

我想建立一個共享服務爲遵循behaviourSubject在angular2,它是如何工作以及如何使用它

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

它拋出一個錯誤。單()/上次()等調用子組件的這個值因陋就簡不是一個函數所以有人告訴我如何實際上工作和如何實現它,因爲我搜索的例子,但沒有任何對我有意義。

回答

19

減少到一個屬性應該看起來像這樣。我改變SharedServicestring,因爲它沒有任何意義,我使用的事件值命名爲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); 
    }); 
    } 
} 
+0

,以及如何以檢索它的價值? 'console.log('behiob'+ shared.space.single());' – Ironsun

+0

我更新了我的答案。 –

+0

你可能只回答上一個問題....反正非常感謝:d – Ironsun

相關問題