4

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!

Erwin
  • 93
  • 1
  • 2
  • 9
  • omitting .map still returns the array object like [object Object]. When I did that below is the snippet looks like. this.http.post(URL, body, options).catch(this.handleError) or this.http.post(URL, body, options) .map().catch(this.handleError) , the latter issues error. – Erwin Oct 19 '16 at 16:38

2 Answers2

3

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);

      }
Community
  • 1
  • 1
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
0
private jsonObj(res: Response) {
    return res.json() || {} ;
}
micronyks
  • 54,797
  • 15
  • 112
  • 146