网站搜索

javascript - 在应用程序或组件加载前运行服务 Angular 7


我正在使用 Angular 7 构建一个应用程序,我已经处理了 API 调用、使用 C# 的 JWT Token 认证系统,以及在必要时更新 LocalStorage(),当用户登录和登出时,所有这些都运行得非常完美。

我的问题是我希望它在应用程序中作为中间件运行登录检查,而不是在生命周期方法 - ng.onInit() 中运行。我该如何做?

有没有一种方法可以将生命周期事件作为入口组件或服务来执行。也就是说,在任何组件加载之前,它能够检查用户是否已登录,并通过路由重定向到所需的页面。

答案#1

守卫是基于路由的……所以我认为你应该更倾向于使用模块/服务的解决方案。

import { APP_INITIALIZER } from '@angular/core';

然后像这样将其添加为提供者:

 export function initApp(initService: YourInitService) {
  return () => { 
    initService.Init();
  }
}
    { provide: APP_INITIALIZER,useFactory: initApp, deps: [YourInitService], multi: true } 

答案#2

你应该在 Angular 中检查 Guard,特别是 canActivate Guard:https://angular.io/guide/router

一个守卫是这样创建的:

@Injectable({
  providedIn: 'root'
})
export class MyGuard implements CanLoad {
 constructor() {}

 canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | 
 Promise<boolean> | boolean {
   const x = true;
   if (x) {
     return true; // It allows access to the route;
   } else {
      // redirect where you want;
     return false; // it doesnt allow to access to the route
  }
 }
}

然后在你的路由模块中:

{
path: "yourRoute",
canActivate: [MyGuard],
component: YourComponent
}

对于身份验证,你有一个很好的库可以在这里使用 guard:https://www.npmjs.com/package/ngx-auth