如果您使用的是Angular 4.3.x及以上版本,请使用来自HttpClientModule
的HttpClient
类:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule
],
...
class MyService() {
constructor(http: HttpClient) {...}
这是从@angular / http模块升级的http
的升级版,具有以下改进: Http
类令牌进行注入,而不是新的 HttpClient
。import { HttpModule } from '@angular/http';
@NgModule({
imports: [
BrowserModule,
HttpModule
],
...
class MyService() {
constructor(http: Http) {...}
此外,新的HttpClient
似乎在运行时需要tslib
,因此您必须安装它npm i tslib
并更新system.config.js
(如果您正在使用SystemJS
):
map: {
...
'tslib': 'npm:tslib/tslib.js',
如果您使用SystemJS,则需要添加另一个映射:
'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
- Tyler O不想重复,但要以其他方式总结(新HttpClient添加的功能):
我写了一篇文章,介绍了旧“http”和新“HttpClient”的区别。目标是以最简单的方式解释它。
http
请求转换为httpClient
。它比较了两者的差异并给出了代码示例。httpClient
时遇到的一些差异(借鉴自我提到的文章):
import {HttpModule} from '@angular/http';
import {HttpClientModule} from '@angular/common/http';
this.http.get(url)
// Extract the data in HTTP Response (parsing)
.map((response: Response) => response.json() as GithubUser)
.subscribe((data: GithubUser) => {
// Display the result
console.log('TJ user data', data);
});
this.http.get(url)
.subscribe((data: GithubUser) => {
// Data extraction from the HTTP response is already done
// Display the result
console.log('TJ user data', data);
});
注意: 您不再需要显式提取返回的数据;默认情况下,如果您收到的数据是JSON类型,则无需执行任何其他操作。
但是,如果您需要解析任何其他类型的响应,例如文本或blob,请确保在请求中添加 responseType
。就像这样:
responseType
选项进行 GET HTTP 请求: this.http.get(url, {responseType: 'blob'})
.subscribe((data) => {
// Data extraction from the HTTP response is already done
// Display the result
console.log('TJ user data', data);
});
我还使用拦截器为每个请求添加我的授权令牌,参考链接.
具体操作如下:
@Injectable()
export class MyFirstInterceptor implements HttpInterceptor {
constructor(private currentUserService: CurrentUserService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// get the token from a service
const token: string = this.currentUserService.token;
// add it if we have one
if (token) {
req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
}
// if this is a login-request the header is
// already set to x/www/formurl/encoded.
// so if we already have a content-type, do not
// set it, but if we don't have one, set it to
// default --> json
if (!req.headers.has('Content-Type')) {
req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
}
// setting the accept header
req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
return next.handle(req);
}
}
这是一个相当不错的升级!
HttpResponse
<T
>>与HttpResponse绑定在一起。这紧密耦合了http层和代码的其余部分。成功:
T
>T
>失败:
TError
>TError
>import { HttpClientExtModule } from 'angular-extended-http-client';
imports: [
.
.
.
HttpClientExtModule
],
//Normal response returned by the API.
export class RacingResponse {
result: RacingItem[];
}
//Custom exception thrown by the API.
export class APIException {
className: string;
}
在你的服务中,只需创建这些回调类型的参数。
然后将它们传递给HttpClientExt的get方法。
import { Injectable, Inject } from '@angular/core'
import { RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.
@Injectable()
export class RacingService {
//Inject HttpClientExt component.
constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {
}
//Declare params of type IObservable<T> and IObservableError<TError>.
//These are the success and failure callbacks.
//The success callback will return the response objects returned by the underlying HttpClient call.
//The failure callback will return the error objects returned by the underlying HttpClient call.
getRaceInfo(success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
let url = this.config.apiEndpoint;
this.client.get(url, ResponseType.IObservable, success, ErrorType.IObservableError, failure);
}
}
在你的组件中,注入了你的服务并调用了以下getRaceInfo API。
ngOnInit() {
this.service.getRaceInfo(response => this.result = response.result,
error => this.errorMsg = error.className);
}
这两个回调函数response和error都是强类型的。例如,response是RacingResponse类型,而error是APIException类型。
在这些强类型的回调函数中,您只需要处理您的模型。
因此,您的其余代码只知道您的模型。
此外,您仍然可以使用传统的方法从服务API返回Observable<HttpResponse<
T>
>。
HttpClient 是一个新的 API,它随着 4.3 版本一起发布,具有更新的 API,支持进度事件、默认的 JSON 反序列化、拦截器和许多其他出色的功能。在这里查看更多信息:https://angular.io/guide/http
Http 是旧的 API,并最终将被弃用。
由于它们在基本任务方面的使用非常相似,因此我建议使用 HttpClient,因为它是更现代和易于使用的替代方案。