我是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;
}
}这个解析器没有返回我试图从我的组件访问的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返回一个空数组。我认为它应该返回我在解析器类中指定的数据。非常需要帮助。谁能告诉我这是怎么回事?提前谢谢。
发布于 2021-02-04 03:31:29
我认为这是Resolve模式的一个边缘情况,你不能在引导组件(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 {}YourDataService
@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))
);
}AppComponent
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
https://stackoverflow.com/questions/66030259
复制相似问题