我的 Angular 应用程序包含一个简单的应用程序,AuthGuard如下所示,并且从未出现过问题。最近,我将 Angular 版本从 15.1.4 升级到 15.2.0,从那时起,我的 IDE 表明 和CanActivate均已CanActivateChild弃用。
Angular 的官方文档说CanActivate:
已弃用:使用纯 JavaScript 函数代替。
我需要如何调整下面的代码以消除已弃用的警告?
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private authService: AuthenticationService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.authService.checkLogin()
.pipe(
map(() => true),
catchError(() => {
this.router.navigate(['route-to-fallback-page']);
return of(false);
}
)
);
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | …Run Code Online (Sandbox Code Playgroud) canactivate angular auth-guard canactivatechild candeactivate
从角文档上canActivate,看来你只能用canActivate后卫,让程序的途径,如果该canActivate函数返回最后true.
有没有办法说,"只有在canActivate课程评估为false" 时才进入这条路线?"
例如,为了不允许登录用户访问登录页面,我尝试了这个但是它不起作用:
export const routes: Route[] = [
{ path: 'log-in', component: LoginComponent, canActivate: [ !UserLoggedInGuard ] },
Run Code Online (Sandbox Code Playgroud)
我在控制台中遇到此错误:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError[false]:
StaticInjectorError[false]:
NullInjectorError: No provider for false!
Error: StaticInjectorError[false]:
StaticInjectorError[false]:
NullInjectorError: No provider for false!
Run Code Online (Sandbox Code Playgroud) typescript angular-routing canactivate angular angular-guards
I got stuck recently with Angular route guards. CanActive runs only once when the page is loaded and does not run on route change within the guarded route. I think this was changed because it used to run on each change. From what I read in forums, I should use CanActivateChild. The thing is, our application consists of several modules, that have several route descendants and when I use CanActivateChild in root module, it is called several times when changing …
我正在使用路由保护,特别是canActivate()方法,但 Angular在调用之前ngOnInit()调用了我的根。AppComponent canActivate
我必须等待一些数据canActivate才能AppComponent在模板中呈现它。
我怎样才能做到这一点?
我正在使用 Angular 6,但我在更改路线时遇到了问题。如果我使用 routerLink 或 navigate() 方法浏览应用程序,它会正常工作,因为它只加载新模块(如有必要)。但是,例如,如果我在此链接中:localhost:8080/home,我单击 URL,取消“主页”,输入“配置文件”并按 Enter,它正确进入配置文件页面,但应用程序已重新加载(也是应用程序组件)。为什么?我想不通。这是我的路由:
const appRoutes: Routes = [
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
Run Code Online (Sandbox Code Playgroud)
也许问题出在 auth-guard 上?
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private store: …Run Code Online (Sandbox Code Playgroud) 我正在Angular 4中编写一个Authguard,以防止在没有登录的情况下访问路由.但是,我收到了这个错误.以下是Authgaurd和Routing in App模块中的代码.请帮助解决问题.
// Authgaurd代码
import { ActivatedRouteSnapshot, CanActivate, Route, Router,
RouterStateSnapshot } from '@angular/router';
import { Store } from '';
import { Observable } from 'rxjs/Observable';
import { map, take } from 'rxjs/operators';
import { Observer } from 'rxjs';
import { Globals } from '../../app.global';
import { CRMStorageService } from '../services/storage.service';
import 'rxjs/add/operator/take';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router,private storageService: StorageService) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
Observable<boolean> {
return this.storageService.getItem(Globals._CURRENT_USER_KEY).take(1).map
(token => { …Run Code Online (Sandbox Code Playgroud) 我的子路由组件正在查询API中的一些数据.目前我正在检查组件,如果通过检查API返回的数据,作为路由参数提供的id是有效的.
我认为这是一种糟糕的风格,并希望将检查放入一个警卫,在组件被激活之前检查提供的参数是否有效.
但是,我也想节省时间和资源.这将需要两个API请求.因此,我想知道是否有可能将数据从防护装置传递给组件.我想过传递路线参数,但canActivate只提供一个ActivatedRouteSnapshot只读的.
因此我的问题是:是否可以将数据从防护组件传递到组件?或者在这种情况下是否有另一种(甚至更好的)方法来节省资源并防止多个API请求?
当我canActivate在路由上添加 AuthGuard 服务时,当我尝试去时应用程序崩溃 /profile并将我重定向到localhost:4200,甚至没有/home并给出以下错误:
错误错误:“[对象对象]”
我的代码:
app.routing.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule, CanActivate } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { LoginComponent } from './login/login.component';
import { AuthGuardService as AuthGuard } from './auth-guard.service';
const routes: Routes = [
{path:'', redirectTo:'/home', pathMatch:'full'},
{path:'home',component: HomeComponent},
{path:'login',component: LoginComponent},
{path:'profile',component: ProfileComponent,canActivate: [AuthGuard]}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
providers: [AuthGuard],
exports: [RouterModule]
})
export class …Run Code Online (Sandbox Code Playgroud)首先,我不确定这是处理这个问题的最佳方法,但我要找的是"/"上的路由保护,它检查用户是否已登录,如果是,则将它们重定向到"/ dashboard" .我想在加载路由之前这样做,以避免屏幕闪烁,因为在远程服务器上检查auth状态.
我正在实现canActivate接口,但它没有按预期工作.它命中auth服务,并返回用户,根据此测试代码应该重定向用户,但我在控制台中看到用户但没有重定向.
这是代码
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { User } from './../../models/user.model';
import { AuthService } from './auth.service';
@Injectable()
export class HomeAuthGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthService
) {}
canActivate(): Promise<boolean> {
return new Promise((resolve) => {
this.authService.getStatus()
.then(function (user: User) {
console.log('home auth', user)
this.router.navigate(['/dashboard']);
resolve(false);
})
.catch(function () {
resolve(true);
});
});
}
}
Run Code Online (Sandbox Code Playgroud) 我有这个AuthGuard:
export class AuthGuard implements CanActivate {
constructor (private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (localStorage.getItem('token')) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我在我的提供AppModule:
@NgModule({
declarations: [/*...*/],
imports: [NotificationRoutingModule],
providers: [AuthService, AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule {
}
Run Code Online (Sandbox Code Playgroud)
我试图在我的路由模块中使用这个后卫,如下所示:
const routes = [
{
path: 'notification',
component: NotificationRootComponent
children: [
{path: '', redirectTo: 'list', pathMatch: 'full'},
{path: 'list', component: NotificationListComponent, canActivate: [AuthGuard]},
{path: ':id', …Run Code Online (Sandbox Code Playgroud) angular ×10
canactivate ×10
typescript ×3
auth-guard ×1
guard ×1
javascript ×1
router ×1
view ×1