2
// user-resolver.service.ts
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { User } from 'firebase/app';
import { Observable } from 'rxjs';
import { AngularFireAuth } from '@angular/fire/auth';

@Injectable()
export class UserResolver implements Resolve<User> {
  constructor(private _firebaseAuth: AngularFireAuth) { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<User> {
    return this._firebaseAuth.authState;
  };
}

//app-routing.module.ts 

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { LoginComponent } from './login/login.component';
import { UserResolver } from './services/user-resolver.service';
import { UserComponent } from './user/user.component';
import { AuthGuardService as AuthGuard } from './services/auth-guard.service';

const appRoutes: Routes = [
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'user', component: UserComponent, resolve: { user: UserResolver }, canActivate: [AuthGuard] },
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  providers: [UserResolver],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule { }

无法导航到 UserComponent 页面。如果我要从路由中删除 resolve 属性,那么它可以工作。但是当试图解析用户时它不起作用。任何帮助表示赞赏。

4

0 回答 0