带有 Akita 状态管理的 Angular 解析器

mar*_*are 3 rxjs angular angular-akita

由于缺乏文档(守卫,解析器,路由几乎没有记录),我在秋田状态管理和使用 Angular 解析器方面苦苦挣扎,到目前为止我一直在路由中使用它(不使用状态管理时)。

我正在查看以下Gist,其中作者确实在组件内订阅,我正在尝试将其移动到解析器。

我尝试了多种变体,包括在解析器中包含以下几行并进行订阅,但没有任何效果:

this.productsService.get().subscribe();

    this.loading$ = this.productsQuery.selectLoading();

    this.products$ = this.search.valueChanges.pipe(
      startWith(''),
      switchMap(value => this.productsQuery.selectAll({
         filterBy: entity => entity.title.toLowerCase().includes(value)
      }))
    );
Run Code Online (Sandbox Code Playgroud)

Baz*_*nga 5

您可以在解析器中获取数据并更新存储。

@Injectable()
class ProductsResolver {
  constructor(private productsService) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<any> {
    return this.productsService.getProducts().pipe(
      tap(products => {
        this.productsService.set(products);
      })
    )
  }
}


class ProductsService {
  constructor(private store: ProductsStore) {

  }

  set(products) {
    this.store.set(products);
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的路线中:

const routes: Routes = [
  {
    path: 'path',
    component: ProductsComponent,
    // The value that returns from the resolver resolve() method
    // will be assign to the products property on ActivatedRoute
    resolve: { products: ProductsResolver }
  }
];
Run Code Online (Sandbox Code Playgroud)

然后在您的组件中:

class Component {
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.products = this.route.snapshot.data['products'];
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我建议不要从解析器返回实际的产品列表 - 而是将它们放入商店(就像您在 Tap 中所做的那样)并返回一个布尔值。例如,您可以在管道末尾添加“mapTo(true)”来实现此目的。为什么?避免有人使用时间点数据而不是查询造成混淆。**您的 Resolve 的目的是确保数据已准备好**,而不是实际返回数据。 (3认同)