如果用户登录,我正在尝试让AuthGuard检查每条路线 . 点击登录按钮后,我转到仪表板页面,一切正常 . 问题是当我通过routerLink单击任何其他路由时,应用程序重新加载并再次重定向到登录页面 .
我想要重现这个项目的作用:Angular-Routes
更新1:更改实现以使用本地存储并且它工作得很好,无论如何,如果路由由角度路由器更改,服务数据不应该在路由之间保留?
这是我的代码:
auth.guard.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;
}
}
auth.service.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.routing.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 {
}
app.module.ts
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>
登录组件
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();
}
}
routerLink示例:
<a class="animsition-link" routerLink="/galeria-midia" routerLinkActive="active">
的package.json
{
"name": "su-backoffice",
"title": "Backoffice Site",
"version": "1.0.0",
"keywords": [
"css",
"js",
"less",
"responsive",
"web",
"admin",
"bootstrap",
"scss"
],
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^5.0.0",
"@angular/common": "^5.0.0",
"@angular/compiler": "^5.0.0",
"@angular/core": "^5.0.0",
"@angular/forms": "^5.0.0",
"@angular/http": "^5.0.0",
"@angular/platform-browser": "^5.0.0",
"@angular/platform-browser-dynamic": "^5.0.0",
"@angular/router": "^5.0.0",
"@ng-select/ng-select": "^0.30.1",
"angular-froala-wysiwyg": "^2.7.6",
"angular2-lightbox": "^1.3.0",
"animsition": "^4.0.2",
"bootstrap": "^4.0.0-alpha.4",
"bootstrap-datepicker": "^1.7.1",
"bootstrap-hover-dropdown": "^2.2.1",
"bootstrap-markdown": "^2.10.0",
"bootstrap-maxlength": "^1.6.0",
"bootstrap-select": "^1.12.4",
"bootstrap-sweetalert": "^1.0.1",
"bootstrap-table": "^1.11.2",
"bootstrap-tagsinput": "^0.7.1",
"bootstrap-tokenfield": "^0.12.0",
"bootstrap-touchspin": "^3.1.1",
"bootstrap-treeview": "^1.2.0",
"core-js": "^2.4.1",
"font-awesome": "^4.7.0",
"jquery": "^3.2.1",
"jquery-asBreadcrumbs": "^0.2.3",
"jquery-asColor": "^0.3.6",
"jquery-asColorPicker": "^0.4.4",
"jquery-asGradient": "^0.3.3",
"jquery-asHoverScroll": "^0.3.6",
"jquery-asPaginator": "^0.3.3",
"jquery-asPieProgress": "^0.4.7",
"jquery-asProgress": "^0.2.4",
"jquery-asRange": "^0.3.4",
"jquery-asScrollable": "^0.4.10",
"jquery-asScrollbar": "^0.5.7",
"jquery-asSpinner": "^0.4.3",
"jquery-contextmenu": "^2.6.3",
"jquery-knob": "^1.2.11",
"jquery-match-height": "^0.7.2",
"jquery-mousewheel": "^3.1.13",
"jquery-placeholder": "^2.3.1",
"jquery-selective": "^0.3.5",
"jquery-slidePanel": "^0.3.5",
"jquery-strength": "^0.2.5",
"jquery-tabledit": "^1.0.0",
"jquery-ui": "^1.12.1",
"jquery-wizard": "^0.4.4",
"jquery.mmenu": "^6.1.8",
"ng2-dnd": "^5.0.2",
"ngx-mydatepicker": "^2.4.4",
"peity": "^3.2.1",
"popper.js": "^1.12.9",
"rxjs": "^5.5.2",
"zone.js": "^0.8.14"
},
"devDependencies": {
"@angular/cli": "1.5.0",
"@angular/compiler-cli": "^5.0.0",
"@angular/language-service": "^5.0.0",
"@types/jasmine": "~2.5.53",
"@types/jasminewd2": "~2.0.2",
"@types/jquery": "^3.2.17",
"@types/node": "~6.0.60",
"autoprefixer": "^7.2.4",
"codelyzer": "~4.0.0",
"jasmine-core": "~2.6.2",
"jasmine-spec-reporter": "~4.1.0",
"karma": "~1.7.0",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.2",
"ts-node": "~3.2.0",
"tslint": "~5.7.0",
"typescript": "~2.4.2"
}
}