29

I am using Angular 2 and getting this error when using an observable Property '_body' does not exist on type 'Response'. The code is below

this.securitiesService.getMarketMovers()
    .subscribe(data => {
        console.log(JSON.parse(data._body))
    });

The getMarketMovers function is simply this:

getMarketMovers() {
    return this._http.get('...url address...')
}

I have tried to set data to type any but that isn't working for me. The code works and there is definitely a _body property on data but it still throws there error and I cant build with this error.

Any help is greatly appreciated.

georgej
  • 3,041
  • 6
  • 24
  • 46

3 Answers3

80

UPDATE

Another way, is to explicitly tell TypeScript that we’re not interested in doing strict type checking.

(<any>data)._body

ORIGINAL

This data["_body"] should work.

koninos
  • 4,969
  • 5
  • 28
  • 47
  • 1
    This helped me in almost exact same situation. Thanks! – mottosson Nov 18 '16 at 10:16
  • 2
    this looks like a hack IMHO, is there better way to check if a Response has empty body? – Toolkit Dec 12 '16 at 13:10
  • This is the only way I could make it work, thank you! :) – balazs630 Oct 18 '17 at 15:16
  • Wow, for anyone looking to fix problems like not being able to access properties coming back from a call, this is your answer! confounded typescript! i read all kinds of stuff like this, but its just Typescript! https://stackoverflow.com/questions/17546953/cant-access-object-property-even-though-it-exists-returns-undefined – russiansummer Nov 02 '17 at 19:20
  • 1
    After 1h... finding this... me like [this](https://media.giphy.com/media/xULW8y5CDynhoSOwVy/giphy.gif). Thanks a lot! – Nicolae Olariu Nov 02 '18 at 14:35
  • I went for the original because it seems way cleaner. Thank you. – Joe Eifert Dec 14 '18 at 11:15
  • 2
    You can also use `(data as any)._body` incase you have a [forbidden angle bracket assertion](https://palantir.github.io/tslint/rules/no-angle-bracket-type-assertion/) – Dylan T. Jun 29 '20 at 20:20
19
data.json();

will give you the json result: https://angular.io/docs/ts/latest/guide/server-communication.html

Chris
  • 1,829
  • 1
  • 15
  • 22
2

to solve this error better way would be to add. : Promise <any> after getMarketMovers() function.

Yogesh Aggarwal
  • 994
  • 7
  • 9