Angular 解析程序未以角度返回数据
我是新来的。我试图在代码中使用解析器。我已经定义了使用解析器的路由。 这是我的路线Angular 解析程序未以角度返回数据,angular,typescript,angular-resolver,Angular,Typescript,Angular Resolver,我是新来的。我试图在代码中使用解析器。我已经定义了使用解析器的路由。 这是我的路线 { path: '', component: AppComponent, resolve: { post: ResolverService } } 然后我创建一个解析器服务 import { Injectable } from '@angular/core'; import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot
{
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;
}
}
这里console.log返回一个空数组。我认为它应该返回我在解析器类中指定的数据。我急需帮助。谁能告诉我发生了什么事?提前感谢。我认为这是一个带有
Resolve
模式的边缘案例,您不能在引导组件(AppComponent)上使用它,因为它不是实际的路由,但应用程序从它开始
如果要为AppComponent
预加载某些内容,可以使用APP\u初始值设定项
,您可以指定任意数量的初始值设定项,并且在它们全部解析之前,应用程序不会启动。他们通过返回来自他们的承诺
来解决问题
应用模块
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))
);
}
应用组件
export class AppComponent {
data = this.yourDataService.demoOnly;
constructor(private yourDataService: YourDataService) {}
}
演示:
export class AppComponent {
data = this.yourDataService.demoOnly;
constructor(private yourDataService: YourDataService) {}
}