Can I return raw json response in angular2

孤街醉人 提交于 2019-12-23 19:57:20

问题


Is it possible for angular2 to return raw json response? Ex.

Component

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

For service

    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{ };
}

The above implementation returns Array . Will there be a way for me to get the raw json data returned by the service? I'm expecting to have json response like below

{ "dataParam": [ { "num": "08", "somestring": "2016-10-03", "somestring2": "2016-10-03" }], "someDatalist": [ { "one": "08", "two": 1, "three": "2016-10-03" }] }

Thanks!


回答1:


Yes off course you can !!

Actually angualar2 returns Response in the form of Observable instead of promise Like in angular1.x , so in order to convert that observable into raw Json format we have to use the default method of angular2 i.e

res.json()

There are no of method apart from .json() provided by angular which can be described here for more info.

methods include

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

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

update

use your code like this

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

      }



回答2:


private jsonObj(res: Response) {
    return res.json() || {} ;
}


来源:https://stackoverflow.com/questions/40136352/can-i-return-raw-json-response-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!