繁体   English   中英

在同一路由 Angular 上将数据从一个解析器传递到另一个解析器

[英]Passing data from one resolver to another on the same route Angular

是否可以在同一路由上将数据从一个解析器传递到另一个解析器?

  {
    path: 'book-view/:id',
    component: BookViewComponent,
    resolve: {
      book: BookViewResolver,
      user: UserResolver
    }
  }

假设我想从 BookViewResolver 中的数据传递数据 (uploader_id) 以从我的 UserResolver 进行 HTTP 调用。

BookView解析器

 export class BookViewResolver implements Resolve<any> {
  constructor(private bookService: BookService) { }

  resolve(route: ActivatedRouteSnapshot) {
    return this.bookService.getBook(route.params['id']);
  }
}

用户解析器

 export class UserResolver implements Resolve<any> {
  constructor(private authService: AuthService) { }

  resolve(route: ActivatedRouteSnapshot) {
    return this.authService.getUser(uploader_id from BookViewResolver);
  }
}

在数据到达最终组件之前。

不,这是不可能的,但我建议您使用 1 个包含 Book 和 AuthService 的解析器,并在这些服务发出和 Observable 时使用RxJS's switchMap

路由器

{
   path: 'book-view/:id',
   component: BookViewComponent,
   resolve: {
     book: BookViewResolver
   } 
}

BookView解析器

export class BookViewResolver implements Resolve<any> {

   constructor(
      private bookService: BookService,
      private authService: AuthService
   ) { }

   resolve(route: ActivatedRouteSnapshot) {
     const id = route.params['id'];

     // After the BookService fetches its corresponding data, you can pass
     // its response to the next call which is the authService and pass the 
     // uploaderId from the response data itself
     return this.bookService
       .getBook(id)
       .pipe(switchMap(data => this.authService.getUser(data.uploaderId)))
   }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM