Angular 5可以激活不起作用

时间:2018-04-02 15:44:20

标签: angular

如果用户登录,我正在尝试让AuthGuard检查每条路线。点击登录按钮后,我转到仪表板页面,一切正常。问题是当我通过routerLink点击任何其他路由时,应用程序重新加载并重新定向到登录页面。

我想要重现这个项目的作用:Angular-Routes

更新1: 更改实现以使用本地存储并且它工作得很好,无论如何,如果路由被角度路由器更改,服务数据不应该在路由之间保留?

这是我的代码:

auth.guard.ts

if [ $answer = "first option" ]; then
    ....
fi

auth.service.ts

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, CanLoad, Route, Router, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from '../auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(
    private authService: AuthService,
    private router: Router
  ) {

  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
    return this.canAccess();
  }

  private canAccess(): boolean {

    if (this.authService.canAccess()) {
      return true;
    }
    this.router.navigate(['/login']);
    return false;
  }
}

app.routing.module.ts

import { EventEmitter, Injectable } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class AuthService {
  private user = false;
  logged = new EventEmitter<boolean>();

  constructor(private router: Router) {

  }

  authUser() {
    this.user = true;
    this.logged.emit(true);
    this.router.navigate(['/']);
  }

  canAccess() {
    return this.user;
  }

}

app.module.ts

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

import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { MidiaGalleryComponent } from './midia-gallery/midia-gallery.component';
import { BannerComponent } from './banner/banner.component';
import { NewsComponent } from './news/news.component';
import { SolutionComponent } from './solution/solution.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './guards/auth.guard';


const appRoutes: Routes = [
  { path: 'dashboard',
    component: DashboardComponent,
    canActivate: [AuthGuard]
  },
  { path: 'galeria-midia',
    component: MidiaGalleryComponent,
    canActivate: [AuthGuard]
  },
  { path: 'banners',
    component: BannerComponent,
    canActivate: [AuthGuard]
  },
  { path: 'noticias',
    component: NewsComponent,
    canActivate: [AuthGuard]
  },
  { path: 'solucoes',
    component: SolutionComponent,
    canActivate: [AuthGuard]
  },
  { path: 'login', component: LoginComponent },
  { path: '', pathMatch: 'full', redirectTo: '/dashboard' }
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes, {enableTracing: true})],
  exports: [RouterModule]
})
export class AppRoutingModule {

}

登录模板

import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NgSelectModule } from '@ng-select/ng-select';
import * as $ from 'jquery';

// Components
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { MidiaGalleryComponent } from './midia-gallery/midia-gallery.component';
import { BannerComponent } from './banner/banner.component';
import { SolutionComponent } from './solution/solution.component';
import { NewsComponent } from './news/news.component';

// Internal Modules
import { NewsModule } from './news/news.module';
import { SharedComponentsModule } from './shared-components/shared-components.module';
import { BannerModule } from './banner/banner.module';
import { SolutionModule } from './solution/solution.module';
import { MidiaGalleryModule } from './midia-gallery/midia-gallery.module';
import { LoginComponent } from './login/login.component';
import { AppRoutingModule } from './app.routing.module';
import { AuthService } from './auth.service';
import { AuthGuard } from './guards/auth.guard';
import { HeaderComponent } from './template/header/header.component';
import { MenuComponent } from './template/menu/menu.component';
import { FooterComponent } from './template/footer/footer.component';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
    MidiaGalleryComponent,
    BannerComponent,
    SolutionComponent,
    NewsComponent,
    LoginComponent,
    HeaderComponent,
    MenuComponent,
    FooterComponent
  ],
  imports: [
    AppRoutingModule,
    BrowserModule,
    FormsModule,
    NewsModule,
    SharedComponentsModule,
    BannerModule,
    SolutionModule,
    NgSelectModule,
    MidiaGalleryModule,
  ],
  providers: [AuthService, AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

登录组件

<div class="vertical-align login-background text-center" data-animsition-in="fade-in" data-animsition-out="fade-out">
  <div class="page-content vertical-align-middle animation-slide-top animation-duration-1">
    <div class="brand">
      <img class="brand-img" src="../../assets/images/img_login_logo.png">
    </div>
    <p class="login-subtitle">Plataforma de conteúdo Unicred</p>
    <form>
      <div class="form-group">
        <label class="sr-only" for="inputEmail">Email</label>
        <input type="email" class="form-control" id="inputEmail" name="email" placeholder="Email">
      </div>
      <div class="form-group">
        <label class="sr-only" for="inputPassword">Password</label>
        <input type="password" class="form-control" id="inputPassword" name="password"
               placeholder="Senha">
      </div>
      <div class="form-group clearfix">
        <div class="checkbox-custom checkbox-inline checkbox-primary float-left">
          <input type="checkbox" id="inputCheckbox" name="remember">
          <label class="remember-me" for="inputCheckbox">Lembre-me</label>
        </div>
        <a class="float-right forgot-password" href="forgot-password.html">Esqueceu a senha?</a>
      </div>
      <button (click)="onSubmit()" type="submit" class="btn btn-primary btn-block">Entrar</button>
    </form>

    <footer class="page-copyright page-copyright-inverse">
      <div class="text-capitalize" >company</div>
      <div class="text-capitalize">© 2018. .</div>
    </footer>
  </div>
</div>

routerLink示例:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private authService: AuthService) { }

  ngOnInit() {
  }

  onSubmit() {
    this.authService.authUser();
  }

}

的package.json

 <a class="animsition-link" routerLink="/galeria-midia" routerLinkActive="active">

0 个答案:

没有答案