angular 路由守卫

1.app创建http-interceptors 文件夹 里面创建http-interceptors.ts 文件

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class BaseInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest, next: HttpHandler): Observable> {
    console.log(req);
    const url = 'https://www.donto.cn:9991';
    let authReq: any;
    if (req.url.indexOf('/connect/token') ===  0) {
      authReq = req.clone({
        url: url + req.url,
      }); // 新增行
    } else {
      const token = localStorage.getItem('token');
      authReq = req.clone({
        url: url + req.url,
        headers: req.headers.set('Authorization', `Bearer ${token}`)
      }); // 新增行
    }

    return next.handle(authReq);
  }
}

2.在app.module.ts引入

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NgZorroAntdModule, NZ_I18N, zh_CN } from 'ng-zorro-antd';
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS, HttpClient } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { registerLocaleData } from '@angular/common';
import zh from '@angular/common/locales/zh';
import { RouterModule } from '@angular/router';
import { RoutesModule } from './routes/routes.module';
import { LayoutModule } from './layout/layout.module';
import { SharedModule } from './shared/shared.module';
import { BaseInterceptor } from './http-interceptors/http-interceptors';

registerLocaleData(zh);

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    NgZorroAntdModule,
    FormsModule,
    HttpClientModule,
    BrowserAnimationsModule,
    RouterModule,
    RoutesModule,
    SharedModule ,
    LayoutModule,
  ],
  providers: [{ provide: NZ_I18N, useValue: zh_CN , } , { provide: HTTP_INTERCEPTORS, useClass: BaseInterceptor, multi: true }, ],
  bootstrap: [AppComponent]
})
export class AppModule {

}

3.守卫 在app里创建auth文件夹
3.1 创建 auth.guard.ts文件 如下:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    const token = localStorage.getItem('token');
    this.authService.isLoggedIn = token ? true : false;
    return this.checkLogin();
  }
  checkLogin(): boolean {
    if (this.authService.isLoggedIn) {
      console.log('登录成功');
      return true;
      }
    // Store the attempted URL for redirecting
    // Navigate to the login page with extras
    this.router.navigate(['/login']);
    return false;
  }
}

3.2在auth里再创建auth.service.ts 文件如下:

import { Injectable } from '@angular/core';

import { Observable, of } from 'rxjs';
import { tap, delay } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  isLoggedIn = false;

  // store the URL so we can redirect after logging in
  redirectUrl: string;

  login(): Observable {
    return of(true).pipe(
      delay(1000),
      tap(val => this.isLoggedIn = true)
    );
  }

  logout(): void {
    this.isLoggedIn = false;
  }
}

完成…

你可能感兴趣的:(技术分享)