Http流发送两次而不是一次 [英] Http stream send twice instead of once

查看:70
本文介绍了Http流发送两次而不是一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我的代码有什么问题.我的服务内容如下:

I am wondering what is wrong with my code. I have the following in my service:

updateCollection(){
    var updateStream = this._http.get('someApi')
        .map((res)=>{
            return res.json();
        })

    updateStream.subscribe(
        success=> {
            this.collection.length = 0;
            console.log('Success in getting collection: ', success.collection);
            (<any>Object).assign(this.collection, success.collection);
            return this.collection;
        }
    );

    return updateStream;
}

getCollection(){
    return this.updateCollection();
}

在我的组件中,我定义了:

And in my component, I have defined:

this._service.getCollection()
        .subcribe(
            success=>{
                console.log("In component", success)
            }
)

但是,从我的Chrome网络和调试程序中可以看到,看来:

However, as I can see from my chrome network and debuggin, it seems that:

this._http.get('someApi')

被调用两次,而不是一次.

is called twice, instead of once.

我想念什么?

推荐答案

那是因为您 subscribe()两次.一次在 updateCollection()内部,一次在 getCollection()中.

That's because you subscribe() twice. Once inside updateCollection() and once in getCollection().

这应该做您想要的:

updateCollection(){
    return this._http.get('someApi')
        .map((res)=>{
           let result = res.json();
           this.collection.length = 0;
           console.log('Success in getting collection: ', success.collection);
            (<any>Object).assign(this.collection, success.collection);
           return result;
        })
        .catch(error => {
          console.log(error);
          return Observable.of([]); to silently continue
          // or return Observable.throw(error);
          // or just throw error;
        });
}

确保您已导入所有内容

import 'rxjs'

import 'rxjs/add/observable/of'
import 'rxjs/add/operator/catch'

这篇关于Http流发送两次而不是一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆