在文件auth-guard-service.ts中,为什么在打印警报消息时调用 this.router.navigateByUrl('/login') 不起作用?另一个文件( auth.service.ts )中的另一个调用正常工作。
auth-guard-service.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { Domain } from 'domain';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
private domain: Domain = new Domain();
constructor(private router: Router) {}
public canActivate(): Observable<boolean>|Promise<boolean>|boolean {
return Observable.create(
(observer) => {
this.domain.isauth()
.subscribe(
(res) => {
observer.next(true);
},
(err) => {
alert('You need to be authentificated to access this content');
// The call to navigateByUrl below does not work. To fix.
this.router.navigateByUrl('/login');
}
);
}
);
}
auth.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { Domain } from 'domain';
import { ConfigService } from './config.service';
@Injectable()
export class AuthService {
private authObject: Observable<boolean>;
private domain: Domain = new Domain();
constructor(private router: Router) {}
public login(login: string, password: string) : void {
this.authObject = this.domain.auth(login, password);
alert('Connecting... Please wait.');
this.authObject.subscribe(
(value) => {
this.router.navigateByUrl('../view/dashboard');
}
);
}
public logout() : void {
alert('Going to logout...');
this.domain.logout();
this.router.navigateByUrl('/login');
}
}
app.routing.ts
import { ModuleWithProviders } from '@angular/core';
import {
Routes,
RouterModule
} from '@angular/router';
import { LoginComponent } from './login';
import {
DashboardComponent,
ViewComponent
} from './view';
import { AuthGuardService } from './services';
const appRoutes: Routes = [
{
path: 'view',
component: ViewComponent,
canActivate: [AuthGuardService],
children: [
{
path: 'dashboard',
component: DashboardComponent
}
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full'
}
]
},
{
path: 'login',
component: LoginComponent
}
{
path: '**',
redirectTo: 'view'
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes, { useHash: true });
如果出现错误(如果用户未连接),我只想重定向到登录页面。
配置:角2