Angular拥有自己的HTTP库,可以用于调用外部API。
在JavaScript世界里有三种方式可以实现异步请求,Callback,Promise与Observable。Angular倾向于使用Observable方式。
HTTP库属于Angular中独立的模块,这意味着当使用时需要导入它。
import {
// The NgModule for using @angular/http
HttpModule,
// the class constants
Http,
Response,
RequestOptions,
Headers
} from '@angular/http';
举个基本的HTTP请求例子:
import { Component, OnInit } from '@angular/core';
import {Http, Response} from '@angular/http';
@Component({
selector: 'app-simple-http',
templateUrl: './simple-http.component.html'
})
export class SimpleHttpComponent implements OnInit {
data: Object;
loading: boolean;
constructor(private http: Http) {
}
ngOnInit() {
}
makeRequest(): void {
this.loading = true;
this.http.request('http://jsonplaceholder.typicode.com/posts/1')
.subscribe((res: Response) => {
this.data = res.json();
this.loading = false;
});
}
}
http.request返回一个Observable,通过subscribe订阅变化。
如果是想要用GET方式请求API的话,可以使用HTTP库中的http.get方法。
@Injectable()
export class YouTubeSearchService {
constructor(private http: Http,
@Inject(YOUTUBE_API_KEY) private apiKey: string,
@Inject(YOUTUBE_API_URL) private apiUrl: string) {
}
search(query: string): Observable<SearchResult[]> {
const params: string = [
`q=${query}`,
`key=${this.apiKey}`,
`part=snippet`,
`type=video`,
`maxResults=10`
].join('&');
const queryUrl = `${this.apiUrl}?${params}`;
return this.http.get(queryUrl)
.map((response: Response) => {
return (<any>response.json()).items.map(item => {
// console.log("raw item", item); // uncomment if you want to debug
return new SearchResult({
id: item.id.videoId,
title: item.snippet.title,
description: item.snippet.description,
thumbnailUrl: item.snippet.thumbnails.high.url
});
});
});
}
}
如果要用POST方式的话,也有http.post方法。
makePost(): void {
this.loading = true;
this.http.post(
'http://jsonplaceholder.typicode.com/posts',
JSON.stringify({
body: 'bar',
title: 'foo',
userId: 1
}))
.subscribe((res: Response) => {
this.data = res.json();
this.loading = false;
});
}
当然还有http.put,http.patch,http.delete以及http.head方法。