Angular 4+ HttpClient

Source: Internet
Author: User
Tags export class

This is a follow-up to the previous angular 4+ http;

Angular version 4.3.0-rc.0 has been released??。 In this release, we waited for an exciting new feature-an improved version of the HTTPClient API;

HttpClient is the evolution of an existing Angular HTTP API, which is in a separate @angular/common/http package. This is to ensure that the existing code base can be slowly migrated to the new API;

Most front-end applications need to communicate with the backend server through the HTTP protocol. Modern browsers support the use of two different APIs to initiate HTTP requests: XMLHttpRequest interfaces and fetch() APIs;

@angular/common/httpHttpClientclass, Angular provides a simplified API for applications to implement HTTP functionality. It is based on the interface provided by the browser XMLHttpRequest . HttpClientOther benefits include testability, strongly-typed request and response objects, interceptor support for initiating and receiving responses, and better, observable (Observable) object-based error handling mechanisms;

1. How to use httpclient;

Import {Ngmodule} from ' @angular/core ', import {browsermodule} from ' @angular/platform-browser '; import { Httpclientmodule} from ' @angular/common/http '; @NgModule ({  imports: [    browsermodule,    //Include it under ' Imports ' in your application module    //after browsermodule.    Httpclientmodule,  ],}) Export class Myappmodule {}

Note: Import the same way as HttpModule, remember to import after Browsermodule, the difference is: in the @angular/common/http module, not @angular/http

So we can use these:

class HttpClient {request (first:string| HttpRequest< any>, url?: String, Options: {...}): Observable< any>Delete (url:string, options: {...}): Observable< any>get (url:string, Options: {...}): Observable< any>Head (url:string, options: {...}): Observable< any>Jsonp<T>(Url:string, callbackparam:string): Observable<T>options (url:string, Options: {...}): Observable< any>Patch (Url:string, Body:any|null, Options: {...}): Observable< any>Post (url:string, Body:any|null, Options: {...}): Observable< any>put (url:string, body:any|null, Options: {...}): Observable< any>}   

2. Initiate a request to obtain JSON data;

First, create a JSON file, which is actually the same JSON file in the previous article:

{"  data": [    {"id": 1, "name": "Windstorm"},    {"id": 2, "name": "Bombasto"},    {"id": 3, "name": "Mag Neta "},    {" id ": 4," name ":" Tornado "}  ]}

How do I invoke an HTTP request?

2.1 app.componment.ts;

Import {Component,oninit} from ' @angular/core ', import {HttpClient} from ' @angular/common/http ';  /* Comment 1*/@Component ({  selector: ' App-root ',  templateurl: './app.component.html ',  styleurls: ['./ App.component.css ']}) Export class AppComponent  implements OnInit {constructor (private http:httpclient) {}  Datas:string[];  Ngoninit () {    this.http.get ('./assets/heroes.json '). Subscribe (data=>{/  * Comment 2*/this.datas=data[         ' Data '];         Console.log (This.datas)}}}   

Attention:

Note 1: httpclient is introduced into the component, and is also in a separate library, @angular/common/http;

Before the introduction of the project has always been HTTP, this is the difference after the revision;

Note 2: JSON is now the default data format, we do not need to do explicit parsing; This.http.get (' xx '). Subscribe ();

Before the need to Res.json () to manually turn;

Another thing to note: I did not go to hero.service.ts inside to operate, but directly in the component request to obtain data, so more simple and clear;

< Div >  < ul   *ngfor = "Let data of Datas" >    < Li > {{data.id}}  {{Data.name}} </ Li >  </ ul > </ Div >

The HTML code is as simple as it is, and it hasn't changed.

This is a simple way to compare the previous HTTP;

  Get (url:string, options: {    headers?: httpheaders,    observe?: Httpobserve,    params?: Httpparams,    reportprogress: boolean,    responsetype?: ' Arraybuffer ' | ' Blob ' | ' JSON ' | ' Text ',    withcredentials?: Boolean,  }): Observable<any>

This is a get method in detail, please note that the return is the observable object, instead of using promise;

3. Response body Check

3.1 In the above code:

Datas:string[];   Define an interface to describe the correct form of this type this.datas=data[' data '; /* Comment 1*/

Note 1:

We need to data[' data 'when we take the data value of the JSON object, not the previous data.data, if we change it to:

This.datas=data.data;

Will error:

Does not exist on type ' Object

That's because the HttpClient JSON-formatted response is parsed into one Object , and it doesn't know what the shape of the object should be. So we should tell you what type of data you need to get, which is more consistent with typescript syntax;

4. What if I'm not going to get a JSON file?

This.http.get ('/assets/1.txt ', {responsetype: ' text '}). Subscribe (      data=>console.log (data))

Note: This allows us to specify the text format to be obtained;

The console will print the contents of my 1.txt: www.sulishibaobei.com

5. How to query data with a parameter

  CONST PARAMS = new Httpparams ()    . Set (' id ', ' 1 '). Set (' Name ', ' windstorm ')    this.cus=this.http.get (' assets/ Heroes.json ', {params})    . Do (Console.log)    . Map (data=>        console.log (_.values (data))
);

Introduced: Httpparams parameters:

Import {HttpClient, httpparams} from ' @angular/common/http ';

We construct the params object by invoking the set () method through the chained syntax, and whenever the set () method is called, it will contain the new values and prevent the previous object from being modified;

Http://localhost:4200/assets/heroes.json?id=1&name=windstorm

The requested link address will be such a form; this is a bit like adding URL parameters to http;

You can also set headers;

Const HEADERS = new Httpheaders (). Set ("X-customheader", "Custom Header value");

There are other requests, which will be analyzed one after the other;

There are also a few more important:

Multiple lines of concurrent sending requests and sequential sending requests, avoid sending duplicate requests;

Avoid sending duplicate requests to import ' Rxjs/add/operator/sharereplay '; const HttpGet = This.http    . Get ("Assets/heroes.json")    . Map ( data = _.values (data))    . Sharereplay (); so that even if you assign the HttpGet to another variable, or repeat the call, it will not be requested again.
One way to send HTTP requests in parallel is to use the forkjoin operator in RxJs: import ' Rxjs/add/observable/forkjoin '; Requests () {    const result = Observable.forkjoin (        this.http.get ('/assets/heroes.json '),        this.http.get (' /assets/heroes.json ')    );   Result.subscribe (        values = {            Console.log ("All Values", values)        }    );
Order send request sequentialrequests () {    const sequence$ = this.http.get<Hero  >('/assets/heroes.json ')        . Switchmap (Hero = {            hero.id+= '-TEST ';            Return this.http.put ('/assets/heroes.json ', Hero)        });            Sequence$.subscribe ();}

6. Interceptors (intercept all requests and responses this is also one of the core features of @angular/common/http)

It can declare some interceptors, blocking between the application and the backend. When an application initiates a request, the interceptor can convert the request before the request is sent to the server. And the response is converted before the application sees the response from the server. This is useful for dealing with a range of tasks, including authentication and logging.

6.1 How to write an interceptor

 import {injectable} from ' @angular/core '; import {httpevent, Httpinterceptor, HttpHandler, HttpRequest, HttpResponse} from ' @angular/common/http '; import {Observable} from ' rxjs/observable '; Injectable () Export class Noopinterceptor implements Httpinterceptor {intercept (req:httprequest  <  any  > , Next : HttpHandler): Observable<  httpevent  Span style= "COLOR: #ff0000" ><any  >   > {return next.handle (req). Map (event = {if (event instanceof HttpResponse) {if (event.stat      US = = = 401) {//JWT expired, go to login}} return event; }   } }

1.interceptis a method that transforms a request object into an observable object (Observable) that returns the response. In this sense, each interceptor has to handle the request entirely on its own;

2. The response interceptor can convert the next.handle(req) response event stream object by applying an additional Rx operator on the returned stream object (that is, the Observable object);

Internal can do their own processing operations;

But at this point the interceptor is not yet used on the component;

Import {Ngmodule} from ' @angular/core ', import {http_interceptors} from ' @angular/common/http '; @NgModule ({  Providers: [{    provide:http_interceptors,    useclass:noopinterceptor,    multi:true,  }], export Class Appmodule {}

Providers inside the configuration of our information;

Note the multi: true options. This is necessary because it tells Angular that this HTTP_INTERCEPTORS represents an array, not a single value;

Angular 4+ HttpClient

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.