在Angular 4上使用Asp Core和asp core的默认模板。守卫工作,但在页面刷新我得到不需要的行为。刷新受保护的路线时,会在canActivate
为true
时简要显示我的登录页面。下图显示了此行为。刷新屏幕时的注意事项闪烁红色(我的登录页面)。
重现问题的步骤:
dotnet new angular
dotnet restore
和npm install
auth.guard.ts
(下面的代码)auth.service.ts
(下面的代码)app.modal.shared.ts
(下面的代码)canActivate
应为true
)如果您希望查看任何其他代码或有任何疑问,请与我们联系。在过去的两天里,我一直在试着使用Observables,地图和订阅等各种各样的东西。任何帮助将不胜感激。提前谢谢!
auth.guard.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router'
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private authService: AuthService,
private router: Router) {
}
canActivate() {
if (!this.authService.isLoggedIn()) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
auth.service.ts
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { Router } from '@angular/router';
import { Response, Headers, RequestOptions } from '@angular/http';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/Rx';
@Injectable()
export class AuthService {
private baseUrl: string = '';
private loggedIn = false;
uid: string | null;
constructor(
private router: Router,
@Inject(PLATFORM_ID) private platformId: Object
) {
if (isPlatformBrowser(this.platformId)) {
this.loggedIn = !!localStorage.getItem('auth_token');
}
}
login() {
this.loggedIn = true;
localStorage.setItem('auth_token', 'test');
}
logout() {
localStorage.removeItem('auth_token');
localStorage.removeItem('uid');
window.location.replace('/home'); // redirect as we want all var and obj to reset
}
isLoggedIn() {
return this.loggedIn;
}
}
app.module.shared.ts
...
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'counter', component: CounterComponent, canActivate: [AuthGuard] },
{ path: 'fetch-data', component: FetchDataComponent, canActivate: [AuthGuard] },
{ path: '**', redirectTo: 'home' }
])
...
编辑:添加了问题的GIF。
编辑:发现这是服务器端预呈现的问题。我目前正在研究如何设置令牌存储服务并将其传递给服务器。