2017-09-26 64 views
0

我想,當一個變量發生變化,所以它似乎是觀察到這裏去 的方式來觸發一個事件是我的服務:認購不觸發

import { Injectable }  from '@angular/core'; 
import {Ad} from './../ad/ad'; 
import {Observable} from 'rxjs/Observable'; 
import { of } from 'rxjs/observable/of'; 

@Injectable() 
export class SearchResultService { 
     public ads : Ad[] = []; 
     getAdsObservable(): Observable<Ad[]> { 
      return Observable.of(this.ads); 
     } 
} 

和組件:

import {Component } from '@angular/core'; 
import {Ad} from './../ad/ad'; 
import {SearchResultService} from './../search/searchResult.service'; 
import {Observable} from 'rxjs/Observable'; 
import { Subscription } from 'rxjs/Subscription'; 


    @Component({ 
     selector: 'map', 

     template : '  
      <div #map id="map" class='main_map' ></div> 
      ', 

    }) 
    export class mapComponent { 
     obs; 
     subscription: Subscription; 
     constructor(
        private searchResultService: SearchResultService, 
        ){ 
     this.obs = this.searchResultService.getAdsObservable(); 


    } 
    ngOnInit(){ 
     this.subscription = this.obs.subscribe( 
      value => { 
       console.log('subscribe trigger'); 

      }); 
     } 

} 

現在的問題是,當searchResultService.ads變化(基本全新廣告加載),它不會觸發認購

+1

工作,我相信你正在尋找一個rxjs主題(https://github.com/Reactive-Extensions/RxJS/blob /master/doc/gettingstarted/subjects.md)這允許您將值推送給主題,訂閱它的任何內容都將監聽更改。 – LLai

回答

1

我相信你想爲這一個主題。 (https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/subjects.md)基本上,你訂閱這個主題,然後當某些東西被推送給主體時,所有的觀察者都會在他們的成功回調中接收到這個值。

// service.ts 
mySubject<Ad[]> = new Subject(); 
ads: Ad[] = []; 

setAd(ad: Ad){ 
    this.ads.push(ad); 
    // anything subscribed to mySubject will receive this.ads when .next() is called 
    this.mySubject.next(this.ads); 
} 

這裏有一個主題(https://plnkr.co/edit/cfWbBIV7hDWRKFfjJlyl?p=preview)的工作plnkr。每當主題收到新值時,打開控制檯查看成功回調。這是一個主題的基本例子。請注意,有不同類型的主題,所以我建議通過他們,看看哪一個最適合您的需求。

+0

謝謝你,是我修改了一下,它工作(公佈最終結果) – pajouk

0

謝謝你,從LLAI答案,我設法得到它使用

import { Injectable }  from '@angular/core'; 
import {Ad} from './../ad/ad'; 
import {BehaviorSubject} from 'rxjs/BehaviorSubject'; 


@Injectable() 
export class SearchResultService { 
    public ads : Ad[] = []; 
    public ads_observable : BehaviorSubject<Ad[]> ; 
    constructor() { 
     this.ads_observable = new BehaviorSubject<Ad[]>(this.ads); 
    } 



    setAds(data){ 
     this.ads = Ad.toObjectArray(data.ads); 
     this.ads_observable.next(this.ads); 

    } 

}