Surendra Kumar
Surendra Kumar

Reputation: 1

What changes are required to use live API in Heroes example in angular 2.0

Given I am new to angular 2.0. I have gone through Heroes example https://angular.io/docs/ts/latest/tutorial/ on this page and need to convert this example to use live APIs. I have created API and cross origin requests are enabled and it has same structure as in memory web API.

I have tried following things, to get it working but no luck.

updated getHeroes() function in hero.service.ts as follows -

getTeams(): Promise<Hero[]> {
        this.http.get('api/heroes')
          .map()
          .then((res: Response) => {
          console.log('RES: ', res);
        }).catch(this.handleError);

        return this.http.get('api/heroes')
                    .toPromise()
                    .then(response => response.json().data as Hero[])
                    .catch(this.handleError);
    }

now above code prints data in console.

but now I updated 'api.heroes' with api URL and in first http and removed following lines from app.modules.ts

import { InMemoryWebApiModule }     from 'angular-in-memory-web-api';
import { InMemoryDataService }      from './in-memory-data.service';
InMemoryWebApiModule.forRoot(InMemoryDataService),

but it says 404 URL not found.

I'm not sure how to implement it.

Upvotes: 0

Views: 112

Answers (1)

nilesh93
nilesh93

Reputation: 419

import 'rxjs/Rx';
import { Http, Response } from '@angular/http';

Import the above and adjust your function like this.

getTeams(){
        this.http.get('http://api/heroes')
                    .map((response: Response) => response.json())
                    .catch(this.handleError)
                    .subscribe((data)=> {

                      // your code here for the data

                      console.log(data)
                     });
    }

Assuming you have initiated Http in the constructor, and your get API is http://api/heroes this should work

Upvotes: 1

Related Questions