文章15
标签3
分类5

angular Loading加载

正文

这几天一直做琢磨 angular 的请求拦截, 两个服务 请求与响应当然也不一定要这样写,我们一般都会在数据请求使用 Loading

推荐一个库

https://github.com/mpalourdio/ng-http-loader

angular antd筛选框的问题

问题

我接收后端发给我的字段 是否记录 他的value值用的数字当我使用 antd 筛选框的时候返回给我的是个 string

<td>
<nz-select ngModel="data?.mode" [nzDropdownStyle]="{background:'#ffffff'}">
              <nz-option nzValue="1" nzLabel="不记录"></nz-option>
              <nz-option nzValue="2" nzLabel="记录"></nz-option>
</nz-select> 
</td>

select.png

<td>
<nz-select [ngModel]="data?.mode" [nzDropdownStyle]="{background:'#ffffff'}">
              <nz-option [nzValue]="1" nzLabel="不记录"></nz-option>
              <nz-option [nzValue]="2" nzLabel="记录"></nz-option>
</nz-select> 
</td>

这样就可以筛选 number 类型的数字了

Angular 请求响应拦截

请求拦截

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class Interceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
       const token :string | null = window.localStorage.getItem('_token');
        if (token) {
            // 设置请求头
            req = req.clone({
                setHeaders: {
                    'token': `${token}`,
                    'Content-Type': 'application/json'
                }
            });
        }
        return next.handle(req);
    }
}

请求的时候 请求头加 token

响应拦截

import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { Injectable } from '@angular/core';
    import { Router ,NavigationExtras} from '@angular/router';
import { catchError, retry } from 'rxjs/operators';
@Injectable()
export class CatchErrorInjector implements HttpInterceptor {
  constructor(public router:Router){}
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return next.handle(req).pipe(
      catchError(err => {
        // token 判空处理
        // 页面响应 loadin 加载
        // 登录持久化
        // 页面骨架
        // 路由跳转
        if(err.error=== 'Unauthorized'){
          console.log('token过期')
          this.router.navigate(['login'])
        }
        throw err;
      }),
    );
  }
}

响应的时候 判断 token 是否过期

// 拦截器
import { HTTP_INTERCEPTORS } from '@angular/common/http';
// 请求
import { Interceptor } from "../server/interceptors";
// 响应
import { CatchErrorInjector } from "../server/CatchErrorInjector";
const HttpInterceptorProviders = [
  { provide: HTTP_INTERCEPTORS, useClass: Interceptor, multi: true },
  { provide: HTTP_INTERCEPTORS, useClass: CatchErrorInjector, multi: true },
]

这是两个服务所以我们要 根模块 providers里引用它

">