-2

OK so I'm primarily a Angular 1.* developer and I thought I'd give angular 5 a try and so far I must say it is giving me hell. Way more complicated than it needs to be but anyhow....

So I make an HTTP call and I have this node API that returns something like this:

apiRoutes.route('/api/code').get(function (req, res) {
...
res.json({status: 200, code: FOO})
});

Meanwhile in Angular 5:

 this.http.get(WEB_CONFIG.API_DOMAIN + 'api/code').subscribe(res => {
            console.log(res) //<----- no error
            console.log(res.code) //<---- Property 'code' does not exist on type 'Object' (WTF)
          });

Why the heck can't I access any of the properties of res(At least at compile time according to VS Code)??? I can see 'res' json in the console if I omit the second log and run the app...

RudolphRedNose
  • 163
  • 1
  • 6
  • 16
  • Are you injecting Http or HttpClient (new in Angular 4.3 and up)? Have you seen the documentation for HttpClient here: https://angular.io/guide/http BTW - I don't think this is a problem with TypeScript but rather with using Angular's HttpClient library. A better title may get you better/more help. – DeborahK Mar 13 '18 at 01:47
  • See this post, it should answer your question. https://stackoverflow.com/questions/39295854/angular-2-how-to-return-data-from-subscribe – Narm Mar 13 '18 at 01:51
  • @Narm I tried to use map() already but VScode tells me 'Property 'map' does not exist on type 'Observable'' I wrapped map() with the 'pipe()' method and that warning went away but I still could not access the json in res. BTW this is using Angular 4+ HTTPClient module which is different form Angular 2's or so I read. – RudolphRedNose Mar 13 '18 at 02:41
  • @DeborahK thanks for pointing me in the right direction – RudolphRedNose Mar 13 '18 at 03:53

2 Answers2

2

Typing return is a good practice, but you don't have too. You can use any

this.http.get(WEB_CONFIG.API_DOMAIN + 'api/code').subscribe((res : any) => {
        console.log(res.code) 
      });
David
  • 33,444
  • 11
  • 80
  • 118
0

OK so I am going to answer my own question. Apparently due to type checking or whatever you want to call it I needed to first:

1.) define an interface to my api. Using angular CLI I did: ng g interface apiConfig.

2.) Configure it making sure that the properties match what is being returned from the API endpoint:

export interface ApiConfig {
status: Number,
code: String
}

3.) Include the interface in my component:

import { ApiConfig } from '../api-config';

4.) Then utilize this syntax in my 'HTTPClient' request:

gCode: ApiConfig

//......... Other stuff........//

this.http.get<ApiConfig>(WEB_CONFIG.API_DOMAIN + 'api/code')
    .subscribe(data => {
      this.gCode = {
        ...data //<----- Yes this weird ellipsis syntax is actually correct
      };
});

I guess I'm just not used to all this type checking in javascript....

RudolphRedNose
  • 163
  • 1
  • 6
  • 16