Diferencia entre HTTP y HttpClient en angular 4?


Quiero saber cuál usar para construir un servicio web simulado para probar el programa Angular?

Author: Aiyoub Amini, 2017-07-16

3 answers

Use la clase HttpClient de HttpClientModule si está utilizando Angular 4.3.x y superiores:

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

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

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

Es una versión actualizada de http desde el módulo @angular/http con las siguientes mejoras:

  • Los interceptores permiten insertar lógica de middleware en la canalización
  • Objetos de solicitud/respuesta inmutables
  • Eventos de progreso tanto para la carga de solicitudes como para la descarga de respuestas

Puedes leer sobre cómo funciona en Insider's guide into interceptors and HttpClient mechanics in Angular .

  • Acceso al cuerpo de respuesta síncrona, incluido el soporte para tipos de cuerpo JSON
  • JSON es un valor predeterminado asumido y ya no necesita ser analizado explícitamente
  • Marco de pruebas basado en verificación posterior a la solicitud y descarga

En el futuro, el antiguo cliente http quedará obsoleto. Aquí están los enlaces al mensaje de confirmación y el oficial docs .

También preste atención a que el antiguo http se inyectó usando Http token de clase en lugar del nuevo HttpClient:

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

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

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

Además, new HttpClient parece requerir tslib en tiempo de ejecución, por lo que debe instalarlo npm i tslib y actualizar system.config.js si está utilizando SystemJS:

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

Y necesita agregar otra asignación si usa SystemJS:

'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
 276
Author: Max Wizard K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-09 16:02:58

No quiero ser repetitivo, pero solo para resumir de otra manera:

  • Conversión automática de JSON a un objeto
  • Definición del tipo de respuesta
  • Evento de disparo
  • Sintaxis simplificada para encabezados
  • Interceptores

Escribí un artículo, donde cubrí la diferencia entre el viejo "http" y el nuevo "HttpClient". El objetivo era explicarlo de la manera más fácil posible.

Simplemente acerca del nuevo HttpClient en Angular

 29
Author: skryvets,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-05 14:21:48

Esta es una buena referencia, me ayudó a cambiar mis solicitudes http a HttpClient

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

Compara los dos en términos de diferencias y da ejemplos de código.

Estas son solo algunas diferencias con las que lidié al cambiar servicios a httpclient en mi proyecto (tomando prestado del artículo que mencioné):

Importando

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

Solicitar y analizar la respuesta

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

Nota: ya no necesita datos explícitamente, por defecto si los datos que obtiene son JSON no tiene que hacer nada extra, pero si necesita analizar cualquier otro tipo de respuesta como texto o blob asegúrese de agregar el tipo responseType en la solicitud. así:

/ / Realiza la solicitud GET HTTP con la opción responseType

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

También utilicé interceptores para agregar el token para mi autorización a cada solicitud:

Esta es una buena referencia: https://offering.soluciones / blog / artículos/2017/07/19/angular-2-new-http-interface-with-interceptors /

Así:

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

Es una actualización bastante agradable!

 9
Author: abann sunny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-04 00:30:48