Angular 2 HTTP Requests with Promise

第一步:模拟restful api,还是以英雄列表为例。(我用的是node+express模拟,禁用同源策略)没什么好说的直接上代码。

var express = require('express');

var app = express();

//设置跨域访问式一 

app.all('*', function (req, res, next) {

res.header("Access-Control-Allow-Origin", "*");

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");

res.header("X-Powered-By", ' 3.2.1')

res.header("Content-Type", "application/json;charset=utf-8");

next();

});

app.get('/heroes', function (req, res) {

//res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问方式二

var ret_obj = [{ "id": 1, "name": "Jackie Chan" }, { "id": 2, "name": "Jet Li" }];

res.end(JSON.stringify(ret_obj));

})

var server = app.listen(8081, function () {

var host = server.address().address

var port = server.address().port

console.log("应用实例,访问地址为ַ:http://%s:%s", host, port)

})

chrome中测试下,结果见下图。

image

第二步:定义英雄结构(hero.ts)

export class Hero {

   id: number;

   name: string;

   constructor(_id: number, _name: string) {

      this.id = _id;

      this.name = _name;

  }

}

第三步:编写英雄服务(hero.service.ts)

import { Injectable } from '@angular/core';

import { Http } from "@angular/http";

import 'rxjs/add/operator/catch';

import 'rxjs/add/operator/toPromise';

import { Hero } from './hero'

@Injectable()

export class HeroService {

heroesUrl = "http://localhost:8081/heroes";

constructor(private http: Http) { }

GetHeores(): Promise<Hero[]> {

return this.http.get(this.heroesUrl)

            .toPromise()

            .then(response => { console.log("Get the heroes from the server side succeeded!"); return response.json() 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);

    }

}

第四步:组件调用(hero.service.ts)

import { Component } from '@angular/core';

import { Hero } from './hero'

import { HeroService } from './hero.service'

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css'],

providers: [HeroService]

})

export class AppComponent {

title = 'Tour of Heroes';

heroes: Hero[];

selectedHero: Hero;

constructor(private heroService: HeroService) { }

getHeroes(): void {

this.heroService

      .GetHeores()

      .then(heroes => { this.heroes = heroes; console.log(heroes) });

  }

ngOnInit(): void {

this.getHeroes();

  }

}

模板文件(app.component.html)如下:

<h1>{{title}}</h1>

<h2>My Heroes</h2>

<ul class="heroes">

<li *ngFor="let hero of heroes">

<span class="badge">{{hero.id}}</span> {{hero.name}}

</li>

</ul>

第五步:chrome中的运行效果:

image

原文地址:https://www.cnblogs.com/rfyuanwei/p/6638930.html