解析器未返回 Angular 中的数据

Resolver is not returning Data in Angular

我是 Angular 的新人。我正在尝试在我的代码中使用解析器。我已经定义了使用解析器的路线。 这是我的路线。

{
   path: '',
   component: AppComponent,
   resolve: {
   post: ResolverService
   }
}

然后我创建一个解析器服务。

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Post } from './post.data';


@Injectable({
  providedIn: 'root'
})

export class ResolverService implements Resolve<any> {

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const post = {
      userId: 101,
      id: 101,
      title: "abc",
      body: "xyz"
    }
    return post;
  }
}

此解析器未 returning 我试图从我的组件访问的 post 数据。这是我的组件 class 代码。

export class AppComponent {
  title = 'angular-resolver';
  page = 1;
  pageSize = 10;

  posts;
  constructor(private route: ActivatedRoute, private postService: PostService) {
  
    this.route.data.subscribe(data => console.log(data));
    
  }
}

这里 console.log 是 returning 一个空数组。我认为它应该 return 我在解析器中指定的数据 class。急需帮助。谁能告诉我这是怎么回事?提前致谢。

我认为这是 Resolve 模式的边缘情况,您不能在 bootstrap 组件 (AppComponent) 上使用它,因为它不是实际路由,但应用程序启动来自它。

如果您想为 AppComponent 预加载某些内容,您可以改用 APP_INITIALIZER,您可以指定任意数量的预加载,应用程序只有在它们全部解析后才会启动。他们通过从他们那里返回 Promise 来解决。

AppModule

export function resolveBeforeAppStarts(yourDataService: YourDataService) {
  return () => yourDataService.load().toPromise();
}

@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [AppComponent],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: resolveBeforeAppStarts,
      deps: [YourDataService],
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

你的数据服务

@Injectable({ providedIn: "root" })
export class YourDataService {
  demoOnly: { userId: number; id: number; title: string; body: string };

  load = () =>
    of({
      userId: 101,
      id: 101,
      title: "abc",
      body: "xyz"
    }).pipe(
      delay(500),
      tap(x => (this.demoOnly = x))
    );
}

应用组件

export class AppComponent {
  data = this.yourDataService.demoOnly;
  constructor(private yourDataService: YourDataService) {}
}

演示:

https://stackblitz.com/edit/angular-ivy-txyfhd?file=src/app/your-data.service.ts