ChuangPoPO / JS_Angular2

1 stars 0 forks source link

issue#13 HTTP #13

Open ChuangPoPO opened 7 years ago

ChuangPoPO commented 7 years ago

In this page, you'll make the following improvements.

You'll teach the app to make corresponding HTTP calls to a remote server's web API.

ChuangPoPO commented 7 years ago

app.moudule.ts

import { HttpModule } from '@angular/http';
imports : [...]
ChuangPoPO commented 7 years ago

Simulate the web API:InMemoryWebApiModule

in-memory-data.service.ts replace mock-heroes.ts

ChuangPoPO commented 7 years ago

Heroes and HTTP

src/app/hero.service.ts

  import { Injectable }    from '@angular/core';
  import { Headers, Http } from '@angular/http';
  import 'rxjs/add/operator/toPromise';
  import { Hero } from './hero';

  private heroesUrl = 'api/heroes';  // URL to web api
  constructor(private http: Http) { }
  getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }

HTTP Promise

Extracting the data in the then callback

Error Handling

Get hero by id

getHero(id: number): Promise<Hero> {
  const url = `${this.heroesUrl}/${id}`;
  return this.http.get(url)
    .toPromise()
    .then(response => response.json().data as Hero)
    .catch(this.handleError);
}
ChuangPoPO commented 7 years ago

in-memory-web-api