在 Angular 中从解析器返回 Observable 的目的

Purpose of returning an Observable from a Resolver in Angular

为什么 return 一个来自 Angular 解析器的 Observable?这与简单地订阅组件本身的 service/store 中的方法有何不同?我认为解析器的目的是确保数据在组件加载之前存在。

来自Angular.IO's documentation about Resolve

Resolve

Interface that classes can implement to be a data provider. A data provider class can be used with the router to resolve data during navigation. The interface defines a resolve() method that will be invoked when the navigation starts. The router will then wait for the data to be resolved before the route is finally activated.

这与简单地 subscribe 调用组件本身 service/store 中的方法不同,因为在那种情况下,加载组件的路由已经被激活并且 API 之后会进行调用。所以用户可能不得不等待数据加载。

现在,在大多数情况下,您一开始就不需要 Resolve。这只是您的 API 响应速度以及获取可能妨碍用户体验的数据是否存在明显延迟的问题。