首页 文章

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

提问于
浏览
197

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

3 回答

  • 33

    如果您使用的是Angular 4.3.x及更高版本,请使用 HttpClientModule 中的 HttpClient 类:

    import { HttpClientModule } from '@angular/common/http';
    
    @NgModule({
     imports: [
       BrowserModule,
       HttpClientModule
     ],
     ...
    
     class MyService() {
        constructor(http: HttpClient) {...}
    

    它是来自 @angular/http 模块的 http 的升级版本,具有以下改进:

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

    您可以在Insider’s guide into interceptors and HttpClient mechanics in Angular中了解它的工作原理 .

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

    继续使用旧的http客户端将被弃用 . 以下是commit messagethe official docs的链接 .

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

    import { HttpModule } from '@angular/http';
    
    @NgModule({
     imports: [
       BrowserModule,
       HttpModule
     ],
     ...
    
     class MyService() {
        constructor(http: Http) {...}
    

    此外,新的 HttpClient 似乎在运行时需要 tslib ,因此如果您使用 SystemJS ,则必须安装 npm i tslib 并更新 system.config.js

    map: {
         ...
        'tslib': 'npm:tslib/tslib.js',
    

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

    '@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
    
  • 294

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

    • 从JSON自动转换为对象

    • 响应类型定义

    • 事件发射

    • 标头的简化语法

    • 拦截器

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

    Simply about new HttpClient in Angular

  • 12

    这是一个很好的参考,它帮助我将我的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';
    

    请求和解析响应

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

    注意:您不再需要显式数据,默认情况下,如果您获得的数据是JSON,您不必再执行任何操作,但如果您需要解析任何其他类型的响应(如text或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);
          });
    

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

    这是一个很好的参考: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);
        }
    }
    

    这是一个非常好的升级!

相关问题