使用Angular Router将一个解析的结果传递给另一个解析

时间:2017-02-14 23:33:56

标签: angular routing resolver

我知道如何为路由创建多个解析类,但我不知道如何将一个解析的结果传递给另一个解析。

// Example Route
{
  path: 'book/:id',
  component: BookComponent,
  resolve: {
    document: BookResolve,
    title: BookTitleResolve
  }
}

如果 BookResolve 返回图书对象,您如何将该图书对象传递给 BookTitleResolve

我有一个标题服务,可以在数据中查找关键标题。我需要能够从书籍对象生成书名。这需要是动态的。

2 个答案:

答案 0 :(得分:3)

在同一个组件中解析并发运行,但父级中的解析将在子级之前完成,因此实现此目的的最简单方法是创建父路由以解析本书。

{
  path: 'book/:id',
  resolve: {
    document: BookResolve
  },
  children: [ {
    path: '',
    component: BookComponent,
    resolve: {
      title: BookTitleResolve
    }
  } ]
}

请注意,父级不呈现组件,并且子级包含空白路径,因此尽管添加了一些样板,但路径的功能应该相同。

然后在BookTitleResolve实现中,您可以从父路径中检索:

class BookTitleResolve {
    resolve(route: ActivatedRouteSnapshot) {
        // Do something with route.parent.data.document
    }
}

答案 1 :(得分:3)

首先,从路由中省略文档解析器,只保留标题解析器(最后一个解析器),如下所示:

// Example Route
{
  path: 'book/:id',
  component: BookComponent,
  resolve: {
    title: BookTitleResolve
  }
}

然后重写BookTitleResolve如下:

export class BookTitleResolve implements Resolve<string> {

    constructor(
      private router: Router,
      private bookResolver : BookResolve,
      private sampleObservableServise : SampleObservableServise
    ) { }

    // add 'async' to resolve method, so we can call resolvers in turn 
    // and wait for response before go to next resolver
    async resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<string> {
  
      // should convert resolver from observable to promise because of using 'await'
      // So, we get bookObject before go to next resolver
      const bookObject = await this.bookResolver.resolve(route, state).toPromise().then( res => {
        return res;
      });
  
  
      // this is final resolver. Again, we should convert resolver from observable to promise
      // because of using 'await'
      return await this.sampleObservableServise.toPromise().then(val => {
        return val
      }, () => {
        this.router.navigate(['/']);
        return null
      })
  
    }
  
  }

总而言之,我们应该只保留路由对象中的最后一个解析器,在这种情况下:

title: BookTitleResolve

然后通过使用 async/await,按照您想要的顺序一一调用其他解析器并使用它们的数据。