從 Angular2 中的 Restful API 讀取
為了將 API 邏輯與元件分開,我們將 API 客戶端建立為單獨的類。此示例類向 Wikipedia API 發出請求以獲取隨機 Wiki 文章。
import { Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
@Injectable()
export class WikipediaService{
constructor(private http: Http) {}
getRandomArticles(numberOfArticles: number)
{
var request = this.http.get("https://en.wikipedia.org/w/api.php?action=query&list=random&format=json&rnlimit=" + numberOfArticles);
return request.map((response: Response) => {
return response.json();
},(error) => {
console.log(error);
//your want to implement your own error handling here.
});
}
}
並有一個元件來使用我們的新 API 客戶端。
import { Component, OnInit } from '@angular/core';
import { WikipediaService } from './wikipedia.Service';
@Component({
selector: 'wikipedia',
templateUrl: 'wikipedia.component.html'
})
export class WikipediaComponent implements OnInit {
constructor(private wikiService: WikipediaService) { }
private articles: any[] = null;
ngOnInit() {
var request = this.wikiService.getRandomArticles(5);
request.subscribe((res) => {
this.articles = res.query.random;
});
}
}