订阅不会触发

时间:2017-09-26 13:46:47

标签: angular angular2-observables

我试图在变量发生变化时触发事件,所以似乎可以观察到observable 这是我的服务:

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发生变化(加载基本新广告)时,它不会触发订阅

3 个答案:

答案 0 :(得分: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。打开控制台以查看每次主题收到新值时触发的成功回调。这是一个主题的基本例子。请注意,有不同类型的主题,所以我建议您浏览它们,看看哪一个最符合您的需求。

答案 1 :(得分:0)

您可以查看ngOnChange,因为您只需在组件初始化时查看信息,您应该要求它在数据流量发生更改后查找数据

cf https://angular.io/guide/lifecycle-hooks

答案 2 :(得分: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);

    }

}