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<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    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<boolean> {
    return of(true).pipe(
      delay(1000),
      tap(val => this.isLoggedIn = true)
    );
  }

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

完成…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值