import {HttpModule} from '@angular/http';
import {HttpClientModule} from '@angular/common/http';
请求和解析响应
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);
});
HttpClient的:
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);
});
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);
}
}
3 回答
如果您使用的是Angular 4.3.x及更高版本,请使用
HttpClientModule
中的HttpClient
类:它是来自
@angular/http
模块的http
的升级版本,具有以下改进:您可以在Insider’s guide into interceptors and HttpClient mechanics in Angular中了解它的工作原理 .
继续使用旧的http客户端将被弃用 . 以下是commit message和the official docs的链接 .
还要注意使用
Http
类令牌而不是新的HttpClient
注入旧的http:此外,新的
HttpClient
似乎在运行时需要tslib
,因此如果您使用SystemJS
,则必须安装npm i tslib
并更新system.config.js
:如果您使用SystemJS,则需要添加另一个映射:
不想重复,只是以其他方式总结:
从JSON自动转换为对象
响应类型定义
事件发射
标头的简化语法
拦截器
我写了一篇文章,其中介绍了旧的“http”和新的“HttpClient”之间的区别 . 目标是以最简单的方式解释它 .
Simply about new HttpClient in Angular
这是一个很好的参考,它帮助我将我的http请求切换到httpClient
https://blog.hackages.io/angular-http-httpclient-same-but-different-86a50bbcc450
它在差异方面对两者进行了比较,并给出了代码示例 .
这只是我在项目中将服务更改为httpclient时所处理的一些差异(借鉴我提到的文章):
输入
请求和解析响应
HTTP
HttpClient的:
注意:您不再需要显式数据,默认情况下,如果您获得的数据是JSON,您不必再执行任何操作,但如果您需要解析任何其他类型的响应(如text或blob),请确保添加responseType请求 . 像这样:
//使用responseType选项发出GET HTTP请求
我还使用拦截器为我的授权添加令牌给每个请求:
这是一个很好的参考:https://offering.solutions/blog/articles/2017/07/19/angular-2-new-http-interface-with-interceptors/
像这样:
这是一个非常好的升级!