第一步:模擬restful api,仍是以英雄列表爲例。(我用的是node+express模擬,禁用同源策略)沒什麼好說的直接上代碼。css
var express = require('express'); html
var app = express(); node
//設置跨域訪問式一 chrome
app.all('*', function (req, res, next) { express
res.header("Access-Control-Allow-Origin", "*"); json
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); api
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); 跨域
res.header("X-Powered-By", ' 3.2.1') restful
res.header("Content-Type", "application/json;charset=utf-8"); app
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中測試下,結果見下圖。
第二步:定義英雄結構(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中的運行效果: