Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 解析程序未以角度返回数据_Angular_Typescript_Angular Resolver - Fatal编程技术网

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) {}
}