解析器未在 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;
  }
}

这个解析器没有返回我试图从我的组件访问的帖子数据。这是我的组件类代码

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 返回一个空数组。我认为它应该返回我在解析器类中指定的数据。非常需要一些帮助。谁能告诉我这是怎么回事?提前致谢。

解决方法

我认为这是 Resolve 模式的边缘情况,您不能在引导程序组件 (AppComponent) 上使用它,因为它不是实际的路由,但应用程序是从它开始的。

如果您想为 AppComponent 预加载某些内容,您可以改用 APP_INITIALIZER,您可以指定任意数量的内容,并且应用程序在它们全部解决之前不会启动。它们通过从它们返回 Promise 来解决。

应用模块

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