如何处理可能为空的rxjs可观察响应? [英] How to handle an rxjs observable response that could be empty?

查看:435
本文介绍了如何处理可能为空的rxjs可观察响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有打字稿的Angular2和Ionic2,并希望处理来自后端服务的响应,我可以获得

I'm using Angular2 and Ionic2 with typescript and would like to handle a response from the backend service where I can get


  • 使用http 200

  • 的空响应或包含errormessage属性的json对象,其中包含要向用户显示的信息。

这是我的要求:

this.http.put(***).subscribe((data) => {

问题是如果我给出data参数,rxjs会尝试序列化它来自json并且如果它是空的,它会抛出一个错误。如果我不提供数据参数我可以处理空响应但是如果我有一个错误消息属性怎么办?

The problem is that if I give the data parameter, rxjs tries to serialize it from json and if that is empty, it throws an error. If I don't give the data parameter I can handle the empty response but how will I reach the errormessage property if I have one?

我不想在后端请求更改,以便在出现错误时提供正确的http错误代码。有没有办法可以解决这个问题?

I don't want to request change on the backend side to give proper http error codes in case of error. Is there a way I can handle this?

推荐答案

您尝试过类似的事情:

public Update = (itemToUpdate: any): Observable<Response> => {
    return this._http
        .put("htto://localhost/api/", JSON.stringify(itemToUpdate))
        .map(res => res ? res.json() : {});
}

这篇关于如何处理可能为空的rxjs可观察响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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