Difference between HTTP and HTTPClient in angular

2019-01-01 04:53发布

问题:

I want to know which one to use to build a mock web service to test the Angular program?

回答1:

Use the HttpClient class from HttpClientModule if you\'re using Angular 4.3.x and above:

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

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

 class MyService() {
    constructor(http: HttpClient) {...}

It\'s an upgraded version of http from @angular/http module with the following improvements:

  • Interceptors allow middleware logic to be inserted into the pipeline
  • Immutable request/response objects
  • Progress events for both request upload and response download

You can read about how it works in Insider’s guide into interceptors and HttpClient mechanics in Angular.

  • Typed, synchronous response body access, including support for JSON body types
  • JSON is an assumed default and no longer needs to be explicitly parsed
  • Post-request verification & flush based testing framework

Going forward the old http client will be deprecated. Here are the links to the commit message and the official docs.

Also pay attention that old http was injected using Http class token instead of the new HttpClient:

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

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

 class MyService() {
    constructor(http: Http) {...}

Also, new HttpClient seem to require tslib in runtime, so you have to install it npm i tslib and update system.config.js if you\'re using SystemJS:

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

And you need to add another mapping if you use SystemJS:

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


回答2:

Don\'t want to be repetitive, but just to summarize in other way:

  • Automatic conversion from JSON to an object
  • Response type definition
  • Event firing
  • Simplified syntax for headers
  • Interceptors

I wrote an article, where I covered the difference between old \"http\" and new \"HttpClient\". The goal was to explain it in the easiest way possible.

Simply about new HttpClient in Angular



回答3:

This is a good reference, it helped me switch my http requests to httpClient

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

It compares the two in terms of differences and gives code examples.

This is just a few differences I dealt with while changing services to httpclient in my project (borrowing from the article I mentioned) :

importing

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

requesting and parsing response

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

Note: you no longer have to data explicitly, by default if the data you get back is JSON you dont have to do anything extra, but if you need to parse any other type of response like text or blob make sure you add the responseType in the request. like so:

// Make the GET HTTP request with responseType option

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

I also used interceptors for adding the token for my authorization to every request:

this is a good reference: https://offering.solutions/blog/articles/2017/07/19/angular-2-new-http-interface-with-interceptors/

like so:

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

Its a pretty nice upgrade!