Resolve Guard:如果没有找到数据,从 Routes 解析可观察对象的正确方法

Resolve Guard: Proper way to resolve observable from Routes, if no data found

angular.io returns 示例中的 resolve 方法如果未找到数据,则承诺或将应用程序导航到特定路径。

resolve(route: ActivatedRouteSnapshot): Promise<any> {
let id = +route.params['id'];
return this.cs.getCrisis(id).then(crisis => {
  if (crisis) {
    return crisis;
  } else { // id not found
    this.router.navigate(['/crisis-center']);
    return false;
  }
});
}

假设 getCrisis 函数返回一个 observable:

resolve(route: ActivatedRouteSnapshot): Observable<any> {
  let id = +route.params['id'];
  return this.cs.getCrisis(id).take(1)
}

在可观察的情况下。当我处理流时,我怎么知道什么都没有返回?在 resolve 函数中处理这种情况的最佳模式是什么?

我知道,我可以使用组件中的 router.navigate 方法,但我想正确使用路由器 resolve guard。

您可能需要添加 .first()(需要导入),因为当前路由器等待 observable 完成并且这可能不会发生,具体取决于 getCrisis() 正在做什么:

resolve(route: ActivatedRouteSnapshot): Observable<any> {
  let id = +route.params['id'];
  return this.cs.getCrisis(id)
  .map(data => {
    if(data) {
      return crisis;
    } else {
      this.router.navigate(['/crisis-center']);
      return false;
    }
  })
  .first()
}

从 angular 6 开始,first() 不在 Observable 中。下面的代码现在可以工作了。

resolve(route: ActivatedRouteSnapshot): Observable<any> {
  let id = +route.params['id'];
  return this.cs.getCrisis(id)
  .map(data => {
    if(data) {
      return crisis;
    } else {
      this.router.navigate(['/crisis-center']);
      return false;
    }
  })
  .pipe(first())
}