函数返回后,Observable.forkJoin调用被延迟

时间:2016-09-12 10:28:27

标签: angularjs angular typescript ecmascript-6 rxjs

在组件中,我们订阅了来自服务的两个http返回结果,并且在服务中,两个http调用正在返回可观察状态。

在组件typscript中

catalogPromise = this.ondemandService.getVodCatalog().subscribe((data) => {
        console.log(data);

        });

在服务中: -

    getVodCatalog(url,user){
    return this.getVodCategories().map((data) => {
            let result,result2;
            let Observers = [],
            cats = [],
            catalogs = [];

            result=data.json();
            result.categorylist.forEach((catergory) => {
                cats.push(catergory.name);
                Observers.push(this.getCategoriesCatolog(catergory.id,{}));
            });
            console.log(Observers);
            Observable.forkJoin(Observers).subscribe((vodCatalogs)=> {
                vodCatalogs.forEach((vodeCatalog,idx)=>{
                    let v1 = vodeCatalog.json();
                    if(v1.vodlist)
                    {
                        catalogs.push({
                            label: cats[idx],
                            list: v1.vodlist
                            });
                    }
                });
                return catalogs;
            });

        })
    .catch(this.handleError);
}


    getVodCategories(){
        let url="http://CategoryList";
        let headers = new Headers({ 'Content-Type':     'application/json','Accept':'application/json, text/plain, */*'});
        let body = {
                offset: 0,
                count: -1,
                type: 'dfasd',
                categoryid: -1,
             };
        let options = new RequestOptions({
             headers: headers,
             url:url,
             withCredentials: true,
             timeout:30000,
             body:body
         });
         return this._http.post(url,body,options);
     }

     getCategoriesCatolog(cateogoryId,options){
         var url="http://VodList";
         let headers = new Headers({ 'Content-Type':    'application/json','Accept':'application/json, text/plain, */*' });
         let body = {
                  count: 100,
                  offset: 0,
                  orderType: 0,
                  categoryid: cateogoryId,
            };
            options = new RequestOptions({
             url:url,
             withCredentials: true,
             timeout:30000,
             body:body
         });
        return this._http.post(url,body,options);
    }

在服务中,getVodCategories()和getCategoriesCatolog()返回可观察的结果,但是当我们尝试在组件中订阅它时,整个数据未定义,之后Observable.forkjoin()正在运行。

1 个答案:

答案 0 :(得分:0)

尽量避免使用嵌套的observable,使用下面的合并insteda

Rx.Observable.merge(
  myService.upload('upload1'),
  myService.upload('upload2')
.take(2)
.subscribe({complete: () => { ... });