Angular 4 HTTP Web API service

Source: Internet
Author: User
Tags export class

Angular HTTP is to get and save data. The main purpose is to fetch data from my JSON file.

Directly on the code bar:

1. First introduce the Promise mode: (direct code)

Heroes.json:

12345678 {    "data" : [      {"id": 1, "name": " Windstorm "},      {" id ": 2," Name ":" Bombasto "},      {" ID ": 3," "Name": "Magneta"},      {"id": 4, "name": "Tornado"}    }

http is sure to have a service, the following first look at the service code: hero.service.promise.ts:

12345678910111213141516171819202122232425262728293031323334 import { Injectable } from ‘@angular/core‘;import { Http, Response }          from ‘@angular/http‘;import { Headers, RequestOptions } from ‘@angular/http‘;import ‘rxjs/add/operator/toPromise‘;import { Hero } from ‘./hero‘;@Injectable()export class HeroService {//注意这里的路径,找的是app文件下的heroes.json文件  private heroesUrl = ‘app/heroes.json‘;  constructor (private http: Http) {}  getHeroes (): Promise<Hero[]> {    console.log(this.heroesUrl);    return this.http.get(this.heroesUrl)                    .toPromise()                    .then(this.extractData)                    .catch(this.handleError);  }  private extractData(res: Response) {    let body = res.json();    return body.data || { };  }  private handleError (error: Response | any) {    let errMsg: string;    if (error instanceof Response) {      const body = error.json() || ‘‘;      const err = body.error || JSON.stringify(body);      errMsg = `${error.status} - ${error.statusText || ‘‘} ${err}`;    } else {      errMsg = error.message ? error.message : error.toString();    }    console.error(errMsg);    return Promise.reject(errMsg);  }}
The main is to provide a getheroes () method:
Here's how it's used in Hero.component.promise.ts:
1234567891011121314151617181920212223 import { Component, OnInit } from ‘@angular/core‘;import { Hero }              from ‘./hero‘;import { HeroService }       from ‘./hero.service.promise‘;@Component({  selector: ‘hero-list-promise‘,  templateUrl: ‘./hero-list.component.html‘,  providers: [ HeroService ],  styles: [‘.error {color:red;}‘]})export class HeroListPromiseComponent implements OnInit {  errorMessage: string;  heroes: Hero[];  mode = ‘Promise‘;  constructor (private heroService: HeroService) {}  ngOnInit() { this.getHeroes(); }  getHeroes() {    this.heroService.getHeroes()                     .then(                       heroes => this.heroes = heroes,                       error =>  this.errorMessage = <any>error);  }}
Of course you have to define a Hero.ts class:
12345 export class Hero {  constructor(    public id: number,    public name: string) { }}

now, what do you think our hero.compoennt.html wrote?

12345 < h1 >tour of Heroes ({{mode}}) </ h1 > < h3 >heroes:</ h3 > < ul > &NBSP;&NBSP; < li *ngfor= "Let Hero of Heroes" >{{hero.name}}</ li > </ ul >

It 's that simple.

Then we introduce our tags in the app.compoennt.ts:
1 <hero-list-promise></hero-list-promise>
The key now is how to configure the Module.ts in the
123456789101112131415161718192021222324 import { NgModule }      from ‘@angular/core‘;import { BrowserModule } from ‘@angular/platform-browser‘;import { FormsModule }   from ‘@angular/forms‘;import { HttpModule, JsonpModule } from ‘@angular/http‘;import { AppComponent }             from ‘./app.component‘;import { HeroListComponent }        from ‘./toh/hero-list.component‘;import { HeroListPromiseComponent } from ‘./toh/hero-list.component.promise‘;@NgModule({  imports: [    BrowserModule,    FormsModule,    HttpModule,    JsonpModule,  ],  declarations: [    AppComponent,    HeroListPromiseComponent,   ],  bootstrap: [ AppComponent ]})export class AppModule {}
The simplest and most common configuration, as usual.

2. The second type is Web API.
There is a file hero-data.ts (there is no need for Heroes.json files here)
123456789101112 import { InMemoryDbService } from ‘angular-in-memory-web-api‘;export class HeroData implements InMemoryDbService {  createDb() {    let heroes = [      { id: 1, name: ‘Windstorm‘ },      { id: 2, name: ‘Bombasto‘ },      { id: 3, name: ‘Magneta‘ },      { id: 4, name: ‘Tornado‘ }    ];    return {heroes};  }}
Module.ts need this configuration: Plus:
12345 import { InMemoryWebApiModule }     from ‘angular-in-memory-web-api‘;import { HeroData }                 from ‘./hero-data‘;imports:[ InMemoryWebApiModule.forRoot(HeroData);]
Hero.service.promise.ts inside need to modify the next path can be. This is to modify the service, the other code do not change.
1 private heroesUrl = ‘api/heroes‘;
There is no relationship with Heroes.json. API is the Web API configured in Module.ts. Angular-in-memory-web-api
Heroes is the return of the heroes inside Hero-data.ts.
These two kinds of results are actually the same.
Let's talk about the observable mode: use is the same.
It's just that the code in the service is different:
Promise Mode:
1234567 getheroes (): promise< hero []> { &NBSP;&NBSP; Console.log (This.heroesurl); &NBSP;&NBSP; return this.http.get (This.heroesurl)                     .topromise ()                     Code class= "HTML Plain" >.then (this.extractdata)                     . catch (This.handleerror); }

The introduction of the package is these few:

1 import ‘rxjs/add/operator/toPromise‘;

The observable pattern is calculated as follows:

12345 getHeroes(): Observable<Hero[]> {  return this.http.get(this.heroesUrl)                  .map(this.extractData)                  .catch(this.handleError);}
Introduced:
123 import { Observable } from ‘rxjs/Observable‘;import ‘rxjs/add/operator/catch‘;import ‘rxjs/add/operator/map‘;
And then it's the same.
Actually proving that fetching JSON data directly is much faster than using the Web API.

Angular 4 HTTP Web API service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.