首页 > 解决方案 > Angular 6 路由器在登录成功后不会在初始导航时导航到第一个延迟加载模块

问题描述

我不明白为什么角路由器在成功登录后忽略/跳过路由器导航。行为就像路由器忽略第一次加载一样。我也试过超时。如果需要任何其他代码,请联系我。一切正常,但在第一次加载时出现此错误。这里 auth.guard.ts。

export class AuthGuard implements CanActivate {
private token;

constructor(
    private router: Router,
    private authService: AuthService,
    private tokenId: SessionService
) {
    this.token = this.tokenId.token;
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.token) {
        return true;
    }
    this.router.navigateByUrl('/login');
    return false;
}    

这里是 login.component.ts

  public async login(data) {
await this.authService.login(data)
  .subscribe((res) => {
    // this.router.navigateByUrl(this.router.createUrlTree(['/']));
    // this.zone.run(() => this.router.navigate(['/']));
    this.router.navigate(['/']);   <======= **this line of code get skipped. I have also tried using async await and setTimeout but nothing works**
  },
    (err) => console.log(err)
  );

}

也试过这个

 // login(data) {
 //   let promise = new Promise((resolve, reject) => {
 //     this.authService.login(data)
 //       .then(async (response) => {
 //         await resolve();
 //         await this.router.navigateByUrl('/');
 //       },
 //         error => {
 //           reject(error);
 //         }
 //       );
 //   });
 //   return promise;
 // }

当前登录方法为 auth.service.ts

public login(data): Observable<any> {
const response = this.http.post(`${localNetwork.apiUrl}/login`, data)
  .pipe(
    map(async res => {
      return res;
    }),
    retry(3),
    catchError(this.handleError)
  );
return response;
}
    // also tried login using promises
// login(data) {
//   this.loader.loading = true;
//   let promise = new Promise((resolve, reject) => {
//     this.http.post(`${localNetwork.apiUrl}/login`, data)
//       .toPromise()
//       .then(
//         async res => {
//           resolve();
//         },
//         error => {
//           reject(error);
//           error = this.handleError;
//         }
//       );
//   });
//   return promise;
// }

private handleError(error: HttpErrorResponse) {
let errMsg = (error.message) ? error.message : error.status ?        `${error.status} - ${error.statusText}` : 'Server error';
return throwError(errMsg);

}

我正在使用角度 v6。当用户在成功登录后首先与应用程序交互时,路由器不会导航到延迟加载的模块

根路由器如下

const routes: Routes = [
{
path: '',
loadChildren: './dashboard/dashboard.module#DashboardModule',
// loadChildren: () => DashboardModule,   <===== also tried this but it having issue: Error as no compiler option
canActivate: [AuthGuard]
},
{
path: 'login',
component: LoginComponent,
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
},
{ path: '**', redirectTo: '' }

];

延迟加载路由模块为 dashboard_routing.module.ts

  const routes: Routes = [
  {
  path: '',
  component: DashboardComponent,
  children: [
  {
    path: '',
    component: HomeComponent,
  },
 ....... <== other routes here
 ]
 }
 ];
 @NgModule({
 imports: [RouterModule.forChild(routes)],
 exports: [RouterModule]
 })
 export class DashboardRoutingModule { }

仪表板模块为 dashboard.module.ts

+imports
 @NgModule({
imports: [
CommonModule,
 ........ <=== other module here
DashboardRoutingModule
   ],
declarations: [
DashboardComponent,
HomeComponent,
],
})
export class DashboardModule { }

我也在另一个版本中检查了相关问题。等待更好的解决方案。如果需要任何相关查询,请联系我。

标签: typescriptangular6router

解决方案


推荐阅读