Angular解析器注入路由器

Angular resolver inject router

我在我的 Angular (v13) 应用程序中定义了一个解析器来使用 wordpress 后端做一些恶作剧。当用户访问 URL 时,我希望解析器从 wordpress 检查 post 类型和 ID,并相应地进行路由(post 列表、单个 post、页面、...) .

为此,我在我的 WordpressResolver class 中注入了 Angular 的路由器,但是当我调用 router.navigate(...) 时,出现以下错误:

ERROR TypeError: Cannot read properties of undefined (reading 'navigate')

好像没有注入路由器,但我不明白为什么。我在解析器上添加了 @Injectable 装饰器,并在路由模块中提供了它。
这是我的路由模块和解析器代码。

app.module.routing.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NotFoundComponent } from './modules/not-found/not-found.component';
import { WordpressResolver } from './wordpress-resolver';

const routes: Routes = [
  {
    path: 'posts',
    loadChildren: () =>
      import('./modules/posts/posts.module').then((m) => m.PostsModule),
  },
  {
    path: 'single/:id',
    loadChildren: () =>
      import('./modules/post/post.module').then((m) => m.PostModule),
  },
  {
    path: 'page/:id',
    loadChildren: () =>
      import('./modules/page/page.module').then((m) => m.PageModule),
  },
  {
    path: '**',
    component: NotFoundComponent,
    resolve: {
      error: WordpressResolver,
    },
  },
];

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

wordpress-resolver.ts

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  Resolve,
  Router,
  RouterStateSnapshot,
} from '@angular/router';
import { environment } from 'src/environments/environment';
import { UrlData } from './shared/model/url-data.interface';
import { UrlType } from './shared/model/url-type.enum';

@Injectable({ providedIn: 'root' })
export class WordpressResolver implements Resolve<HttpErrorResponse | null> {
  constructor(private http: HttpClient, private router: Router) {}

  private error: HttpErrorResponse | null = null;

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): HttpErrorResponse | null {
    this.http
      .get<UrlData>(environment.domain + state.url)
      .subscribe(this.resolveSuccess, this.resolveError);

    return this.error;
  }

  private resolveSuccess(urlData: UrlData): void {
    switch (urlData.type) {
      case UrlType.POSTS:
        this.router.navigate(['/posts'], { skipLocationChange: false });
        return;
      case UrlType.POST:
        this.router.navigate(['/post', urlData.id], {
          skipLocationChange: false,
        });
        return;
      case UrlType.PAGE:
        this.router.navigate(['/page', urlData.id], {
          skipLocationChange: false,
        });
        return;
      default:
        return;
    }
  }
  private resolveError(error: HttpErrorResponse): void {
    this.error = error;

    this.router.navigate(['/error'], {
      skipLocationChange: true,
    });
  }
}

(我知道“/error”尚未映射,这是一项正在进行的工作)

您必须将回调函数定义为箭头函数,以便您可以访问全局范围

resolveSuccess= (urlData: UrlData): void => { }