使用combineLatest检测是否找不到Observable

时间:2016-02-01 19:54:34

标签: angularjs angular observable

我需要修改我的代码,其中加载详细信息类别将首先查看它是否尚未在语句中加载,如果没有,则加载详细信息。谢谢你的帮助!

CategoryProvider的构造函数:

private _obServers = {
    'categoryList': undefined,
    'category': undefined,
    'idCategory': new Subject<Number>()
};

constructor(){
    this.categories = new Observable(observer => this._obServers.categoryList = observer).share();

    this._categoryObservable = this.categories
        .combineLatest(this._obServers.idCategory, (categories, idCategory) => {
            return categories.filter(category => category.id === idCategory)[0];
        })
        .distinctUntilChanged((oldCategory, newCategory) => {
            return oldCategory.id === newCategory.id;
        });
}

所属分类:

loadCategories(search?:string):void{
    this._http
        .get('/services/category/list?search=' + search)
        .map(res => res.json())
        .subscribe(data => {
            this._obServers.categoryList.next(this.createCategoryEntities(data));
        });
}

CategoryDe​​tail:

loadCategory(categoryId:number){

    this._obServers.idCategory.next(categoryId);

    //If category not loaded I need to load it

}

1 个答案:

答案 0 :(得分:1)

我按照这种方式https://github.com/JonatanSCS/Angular-2-Tutorial/blob/master/node_modules/rxjs/src/add/observable/combineLatest.ts

import { Component, Injectable, Inject, provide } from '@angular/core';
import { HTTP_PROVIDERS } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { combineLatestStatic } from 'rxjs/operator/combineLatest.js';

import { MessageApi } from '../providers/lb-service/lb-services.provider'
import { EstimatesService } from './estimates.service';


@Component({
    pipes: [TranslatePipe],
})

@Injectable()
export class InvoiceService {

    constructor(private _message:MessageApi,
                @Inject(EstimatesService) _estimates:EstimatesService) {
        this._message = _message;
        this._estimates = _estimates;

        Observable.combineLatest = combineLatestStatic;

        declare module 'rxjs/Observable' {
            namespace Observable {
                export let combineLatest: typeof combineLatestStatic;
            }
        }

        Observable.combineLatest(
            this._estimates.getEstimates(),
            this._message.findOne({
                    where: {
                        moduleTag: 'monthlyStat',
                        'dynamic.date': "2016-07-01" //new Date
                    },
                    fields: {
                        dynamic: true
                    }
                }),this._message.findOne({
                where: {
                    moduleTag: 'areaPriceSE1',
                    'dynamic.date': ''
                },
                fields: {
                    dynamic: true
                }
            })
        ).subscribe(res => console.log("observable", res));