In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Most people don't understand the knowledge points of this article "How Angular intercepts and encapsulates requests", so Xiaobian summarizes the following contents for everyone. The contents are detailed, the steps are clear, and they have certain reference value. I hope everyone can gain something after reading this article. Let's take a look at this article "How Angular intercepts and encapsulates requests".
区分环境
我们需要对不同环境下的服务进行拦截。在使用 angular-cli 生成项目的时候,它已经自动做好了环境的区分,在 app/enviroments 目录下:
environments ├── environment.prod.ts // 生产环境使用的配置└── environment.ts // 开发环境使用的配置
我们对开发环境进行修改下:
// enviroment.tsexport const environment = { baseUrl: '', production: false};
baseUrl 是在你发出请求的时候添加在请求的前面的字段,他指向你要请求的地址。我什么都没加,其实等同加了 http://localhost:4200 的内容。
当然,你这里添加的内容要配合你代理上加的内容调整,读者可以自己思考验证
添加拦截器
我们生成服务 http-interceptor.service.ts 拦截器服务,我们希望每个请求,都经过这个服务。
// http-interceptor.service.tsimport { Injectable } from '@angular/core';import { HttpEvent, HttpHandler, HttpInterceptor, // 拦截器 HttpRequest, // 请求} 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, next: HttpHandler): Observable { let secureReq: HttpRequest = req; secureReq = secureReq.clone({ url: environment.baseUrl + req.url }); return next.handle(secureReq).pipe( tap( (response: any) => { // 处理响应的数据 console.log(response) }, (error: any) => { // 处理错误的数据 console.log(error) } ) ) }}
要想拦截器生效,我们还得在 app.module.ts 上注入:
// app.module.tsimport { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';// 拦截器服务import { HttpInterceptorService } from './services/http-interceptor.service';providers: [ // 依赖注入 { provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true, }],
验证
到这里,我们已经成功的实现了拦截器。如果你运行 npm run dev,你会在控制台上看到下面的信息:
To verify that content credentials are required to access content, I tried using the [post] https://jimmyarea.com/api/private/leave/message interface and got the following error:
The backend has processed this interface and requires credentials to operate, so an error 401 is reported directly.
Well, here's the problem. After we log in, how do we bring our credentials?
As follows, we modify the content of the interceptor below:
let secureReq: HttpRequest = req;// ...// Use localhost to store user credentials, and if (window.localStorage.getItem ('ut ')) { let token = window.localStorage.getItem ('ut')} on the request header|| '' secureReq = secureReq.clone({ headers: req.headers.set('token', token) });}// ...
The validity period of this certificate requires the reader to determine whether the validity period is valid when entering the system, and then consider resetting the value of localstorage, otherwise it will always report an error. This is also very simple. It is convenient to encapsulate localstorage.
The above is the content of this article about "How Angular intercepts and encapsulates requests." I believe everyone has a certain understanding. I hope the content shared by Xiaobian will help everyone. If you want to know more relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.