角度4中的HTTP和HTTPClient之间的区别?

Aiy*_*ini 224 angular2-http angular angular-httpclient

我想知道使用哪一个来构建模拟Web服务来测试Angular程序?

Max*_*kyi 334

使用HttpClient从类HttpClientModule,如果你采用了棱角分明的4.3.x及以上:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
 imports: [
   BrowserModule,
   HttpClientModule
 ],
 ...

 class MyService() {
    constructor(http: HttpClient) {...}
Run Code Online (Sandbox Code Playgroud)

它是httpfrom @angular/httpmodule 的升级版本,具有以下改进:

  • 拦截器允许将中间件逻辑插入管道
  • 不可变的请求/响应对象
  • 请求上载和响应下载的进度事件

您可以在Insider的拦截器指南和Angular中的HttpClient机制中阅读它的工作原理.

  • 类型化的同步响应主体访问,包括对JSON主体类型的支持
  • JSON是假定的默认值,不再需要显式解析
  • 请求后验证和基于刷新的测试框架

继续使用旧的http客户端将被弃用.以下是提交消息官方文档的链接.

还要注意使用Http类令牌而不是新的注入旧的http HttpClient:

import { HttpModule } from '@angular/http';

@NgModule({
 imports: [
   BrowserModule,
   HttpModule
 ],
 ...

 class MyService() {
    constructor(http: Http) {...}
Run Code Online (Sandbox Code Playgroud)

此外,新的HttpClient似乎需要tslib在运行时,所以你必须安装它npm i tslib并更新,system.config.js如果你正在使用SystemJS:

map: {
     ...
    'tslib': 'npm:tslib/tslib.js',
Run Code Online (Sandbox Code Playgroud)

如果您使用SystemJS,则需要添加另一个映射:

'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
Run Code Online (Sandbox Code Playgroud)

  • 我遇到了同样的问题(我正在使用System.js).这个答案中缺少的一件事是你还需要在system.js中映射新模块,如下所示:`'@ angular/common/http':'npm:@angular/common/bundles/common-http .umd.js',` (5认同)

skr*_*ets 43

不想重复,只是以其他方式总结:

  • 从JSON自动转换为对象
  • 响应类型定义
  • 事件解雇
  • 标头的简化语法
  • 拦截器

我写了一篇文章,其中我介绍了旧的"http"和新的"HttpClient"之间的区别.目标是以最简单的方式解释它.

关于Angular中的新HttpClient


aba*_*nny 17

这是一个很好的参考,它帮助我将我的http请求切换到httpClient

https://blog.hackages.io/angular-http-httpclient-same-but-different-86a50bbcc450

它在差异方面对两者进行了比较,并给出了代码示例.

这只是我在项目中将服务更改为httpclient时所处理的一些差异(借鉴我提到的文章):

输入

import {HttpModule} from '@angular/http';
import {HttpClientModule} from '@angular/common/http';
Run Code Online (Sandbox Code Playgroud)

请求和解析响应:

@角/ 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);
      });
Run Code Online (Sandbox Code Playgroud)

@角/普通/ HTTP

 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);
      });
Run Code Online (Sandbox Code Playgroud)

注意:您不再需要显式提取返回的数据; 默认情况下,如果您获取的数据是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);
      });
Run Code Online (Sandbox Code Playgroud)

添加拦截器

我还使用拦截器为我的授权添加令牌给每个请求:

这是一个很好的参考:https: //offering.solutions/blog/articles/2017/07/19/angular-2-new-http-interface-with-interceptors/

像这样:

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个非常好的升级!