Make writing a habit together! This is the sixth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details

In the previous Angular article using Api proxies, we dealt with the issue of the local mediation interface, using proxies.

Our interfaces are written and handled separately, and in real development projects there are many interfaces, some requiring login credentials and some not. Can we consider intercepting and encapsulating the request?

This article to achieve.

To distinguish the environment

We need to intercept services in different environments. When using angular-CLI to generate a project, it automatically distinguishes the environment in the app/enviroments directory:

Environments ├ ─ ─ environment. Prod. Ts / / production environment using configuration └ ─ ─ the environment. The ts / / use the development environment configurationCopy the code

Let’s modify the development environment:

// enviroment.ts

export const environment = {
  baseUrl: ' '.production: false
};
Copy the code

BaseUrl is the field added to the front of the request when you make it, which points to the address you want to request. I did not add anything, in fact, equivalent to the content of http://localhost:4200.

Of course, the content you add here should be adjusted with the content you add on the agent, the reader can think about verification

Adding interceptors

We generate the service HTTP-Interceptor.service. ts interceptor service, which we want every request to pass through.

// http-interceptor.service.ts

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor, / / the interceptor
  HttpRequest, / / request
} from '@angular/common/http';

import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any> > {let secureReq: HttpRequest<any> = req;

    secureReq = secureReq.clone({
      url: environment.baseUrl + req.url
    });

    return next.handle(secureReq).pipe(
      tap(
        (response: any) = > {
          // Process the data for the response
          console.log(response)
        },
        (error: any) = > {
          // Handle bad data
          console.log(error)
        }
      )
    )
  }
}
Copy the code

For the interceptor to work, we also need to inject app.module.ts:

// app.module.ts

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
// Interceptor service
import { HttpInterceptorService } from './services/http-interceptor.service';

providers: [
  // dependency injection
  {
    provide: HTTP_INTERCEPTORS,
    useClass: HttpInterceptorService,
    multi: true,}],Copy the code

validation

At this point, we have successfully implemented the interceptor. If you run NPM run dev, you should see the following message on the console:

Want to verify whether need content credentials to access to content, here I use the interface [post] https://jimmyarea.com/api/private/leave/message try, get the following error:

The backend has processed that this interface needs credentials to operate, so error 401 is reported directly.

So, here’s the problem. After we log in, how do we need to bring our credentials?

Here, we modify the interceptor content:

let secureReq: HttpRequest<any> = req;
// ...
// Use localhost to store user credentials in the request header
if (window.localStorage.getItem('ut')) {
  let token = window.localStorage.getItem('ut') | |' '
  secureReq = secureReq.clone({
    headers: req.headers.set('token', token)
  });
}

// ...
Copy the code

The validity period of this certificate, the reader needs to enter the system, determine whether the validity period is valid, and then consider resetting the value of localstorage, otherwise it will always report an error, this is also very simple, relevant to localstorage encapsulation convenient operation can be ~

【 the 】 ✅