从 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;
});
}
}