Angular- AuthGuard不工作

时间:2017-11-12 14:10:18

标签: angular routing angular-routing angular-router

我已经在Angular 5中尝试了!/usr/bin/ruby class Customer @@total_customers = 0 def initialize(id, name, addr) @cust_id = id @cust_name = name @cust_addr = addr @@total_customers +=1; end def display_details() puts "Customer id #{@cust_id}" puts "Customer name #{@cust_name}" puts "Customer address #{@cust_addr}" end def total_no_of_customers() puts "Total number of customers: #{@@total_customers}" end end 但它现在按预期工作了,我也没有收到任何错误。请帮我解决这个问题。即使CanActivate也没有实例化。我只想在用户登录时才进行路由。一旦用户登录,我将存储在authguard并在auth guard中检索相同的内容。

session storage
    // AuthGuard
    import { MatSnackBar } from '@angular/material';
    import { Router } from '@angular/router';
    import { Injectable } from '@angular/core';
    import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from 
    '@angular/router';
    import { Observable } from 'rxjs/Observable';

  @Injectable()
  export class AuthGuard implements CanActivate {
  constructor(private router: Router,  private snackBar: MatSnackBar) {}

  canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | 
  boolean {
        if (sessionStorage.getItem('token')) {
            return true;
       } else {
           this.router.navigateByUrl('/login');
          this.snackBar.open('Please Login to Continue');
       }
    }
}
    //Routing 
    import { AuthGuard } from './guards/auth.guard';
    import { LoginComponent } from './components/login/login.component';
    import { RegistrationComponent } from 
    './components/registration/registration.component';
    import { UploadComponent } from './components/upload/upload.component';
    import { RouterModule, Routes, CanActivate, CanActivateChild } from '@angular/router';
    import { ProductComponent } from './components/product/product.component';
    import { CategoryComponent } from './components/category/category.component';

    export const appRoutes = [
        {
          path: 'category',
          component: CategoryComponent,
          CanActivate: [ AuthGuard ]
        },
        {
          path: 'product',
          component: ProductComponent
        },
        {
          path : 'upload',
          component : UploadComponent
        },
        {
          path : 'register',
          component: RegistrationComponent
        },
        {
          path : 'login',
          component: LoginComponent
        }
    ];

1 个答案:

答案 0 :(得分:1)

您忘了在app.module中提供它。将AuthGuard添加到providers数组。它也应该是canActivate,而不是CanActivate