我是角度7的newbee,现在正尝试实现CanActive,但出现错误:
任何人都可以引导我克服这一问题。我的代码示例如下:
auth.guard.ts:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth-service.service';
import {Router} from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private auth: AuthService,
private myRoute: Router){
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if(this.auth.isLoggednIn()){
return true;
}else{
this.myRoute.navigate(["login"]);
return false;
}
}
}
答案 0 :(得分:1)
请尝试以下操作:
return this.auth.isLoggednIn() ? true : this.myRoute.navigate(["login"]);
执行以下操作时,我收到相同的错误消息:
canDeactivate(component: CreateEmployeeComponent): boolean {
if(component.createEmployeeForm.dirty) {
return confirm('Are you sure you want to discard your changes?');
}
return true;
}
所以我通过以下方式解决了这个问题:
canDeactivate(component: CreateEmployeeComponent): boolean {
return component.createEmployeeForm.dirty
? confirm('Are you sure you want to discard your changes?')
: true;
}
我不确定它是否适合您,但您至少可以尝试一下。
答案 1 :(得分:0)
在if
条件下使用promise始终是个坏主意,因为它无法解决。您可以返回承诺本身,使用resolve
将结果布尔值进一步传递给行:
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Promise<boolean> | boolean {
return new Promise(resolve =>
this.auth.isLoggednIn()
.then(status: boolean => {
if(status === false) {
this.myRoute.navigate(["login"]);
}
resolve(status);
})
.catch(() => {
this.myRoute.navigate(["login"]);
resolve(false);
// ... or any other way you want to handle such error case
})
}
}
答案 2 :(得分:-1)
检查提供给路由的类(在本例中为 struct BookReader: App {
@StateObject var library = Library()
var body: some Scene {
WindowGroup {
LibraryView()
.environmentObject(library)
}
}
}
struct LibraryView: View {
@EnvironmentObject var library: Library
// ...
}
)MyGuardClass
实现了 {path: 'aPath', component: myComponent, canActivate: [MyGuardClass]}
as documented here