【问题标题】:Get async data with Angular resolver使用 Angular 解析器获取异步数据
【发布时间】:2019-08-03 04:31:09
【问题描述】:

我的 Angular 8 应用中有解析器

export class UserResolver implements Resolve<any> {

  constructor(
    private authService: AuthService,
  ) { }

  resolve() {
    this.authService.user.subscribe(user => {
      return user
    })
  }
}

但这是将null 分配给路由器数据,因为user 在我的服务中带有异步功能(它来自主题)。如何让解析器等待从我的服务返回的数据,而不是为数据分配空值?

【问题讨论】:

  • 你能分享一下你用过UserResolver的路由配置吗?

标签: angular rxjs


【解决方案1】:

两件事:

1) 删除subscribe 并让解析器处理订阅。

2) 返回 Observable,而不是数据。

类似这样的:

export class UserResolver implements Resolve<any> {

  constructor(
    private authService: AuthService,
  ) { }

  resolve() {
    return this.authService.user;
  }
}

更新:

我的工作,等待然后返回数据。我的看起来像这样:

constructor(private productService: ProductService) { }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<IProduct> {
        const id = +route.paramMap.get('id');
        return this.productService.getProduct(id);
    }

请注意,没有订阅,我正在返回从 http get 操作返回的 Observable。

我的路由配置如下:

@NgModule({
  imports: [
    SharedModule,
    InMemoryWebApiModule.forRoot(ProductData),
    RouterModule.forChild([
      { path: 'products', component: ProductListComponent },
      {
        path: 'products/:id',
        component: ProductDetailComponent,
        resolve: { resolvedData: ProductResolver }
      },
      {
        path: 'products/:id/edit',
        component: ProductEditComponent,
        resolve: { resolvedData: ProductResolver }
      }
    ])

如果你想要工作代码,我这里有一个更复杂的版本(由于添加了异常处理而更复杂):https://github.com/DeborahK/Angular-Routing/tree/master/APM-Final

【讨论】:

  • 它永远不会返回数据,如果我将代码更改为此页面将无法加载。
  • 你在路由配置中配置得当吗?
  • 是的,如果我只从解析器组件返回一个字符串接收它
  • 我更新了上面的内容以包含指向工作解析器的链接。如果这没有帮助,请考虑构建一个说明您的问题的 stackbltiz,我们可以仔细研究一下。
猜你喜欢
  • 2013-08-02
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-10
相关资源
最近更新 更多