【问题标题】:Can I return raw json response in angular2我可以在 angular2 中返回原始 json 响应吗
【发布时间】:2016-10-19 15:56:30
【问题描述】:

angular2 是否可以返回原始 json 响应?例如。

组件

getrawJson(){
    this.someservice.searchJson()
    .subscribe( somelist => this.somelist = somelist,
                 error => this.errorMsg = <any>error);
}

为了服务

    searchJson(num: number, somestring: string, somestring2: string): Observable<stringDataObj> {

        let body = JSON.stringify({"someJsonData"[{num, somestring, somestring2}]}); 
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });


        return this.http.post(URL, body, options)
                        .map(this.jsonObj)
                        .catch(this.handleError);

      }


private jsonObj(res: Response) {
    let body;
    return body{ };
}

上述实现返回 Array 。我有办法获取服务返回的原始 json 数据吗?我希望得到如下的 json 响应

{ “数据参数”:[{ “数字”:“08”, "somestring": "2016-10-03", “somestring2”:“2016-10-03” }], “一些数据列表”:[{ “一”:“08”, “二”:1、 “三”:“2016-10-03” }] }

谢谢!

【问题讨论】:

  • 省略 .map 仍会返回数组对象,如 [object Object]。当我这样做时,下面是 sn-p 的样子。 this.http.post(URL, body, options).catch(this.handleError) 或 this.http.post(URL, body, options) .map().catch(this.handleError) ,后者发出错误。

标签: json angular jsonresponse


【解决方案1】:

当然可以!!

实际上 angualar2 以 Observable 的形式返回 Response 而不是 angular1.x 中的 promise ,因此为了将 observable 转换为原始 Json 格式,我们必须使用 angular2 的默认方法,即

res.json()

除了 angular 提供的 .json() 之外没有其他方法,可以在此处描述以获取更多信息。

方法包括

  • res.text()
  • res.status
  • res.statusText 等等

https://angular.io/docs/ts/latest/api/http/index/Response-class.html

更新

像这样使用你的代码

return this.http.post(URL, body, options)
                        .map(res => {return res.json()})
                        .catch(this.handleError);

      }

【讨论】:

  • 如果我使用它,它将返回 [object Object] 。
【解决方案2】:
private jsonObj(res: Response) {
    return res.json() || {} ;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    • 2021-08-12
    • 2017-10-14
    • 2017-05-05
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    相关资源
    最近更新 更多