3

Due to lacking docs (guards, resolvers, routing almost not documented) I'm struggling with Akita state management and the use of Angular resolvers which I always used so far with routing (when not using state mgmt).

I'm looking at the following Gist where author does subscribe inside the component and I'm trying to move that to the resolver.

I've tried multiple variations of including the following lines in resolver and doing subscribe but nothing worked:

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)
      }))
    );
mare
  • 13,033
  • 24
  • 102
  • 191

1 Answers1

5

You can fetch the data in the resolver and update the store.

@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);
  }
}

In your routes:

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 }
  }
];

Then in your component:

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

  ngOnInit() {
    this.products = this.route.snapshot.data['products'];
  }
}
Bazinga
  • 10,716
  • 6
  • 38
  • 63
  • please add how does the 'products' get to the route snapshot data because it is not clear from the above example – mare Dec 01 '18 at 23:20
  • I added what you asked. – Bazinga Dec 02 '18 at 06:03
  • 3
    I'd recommend not returning the actual list of products from the resolver - instead just put them in the store (as you did in tap) and instead return a boolean. For example you could add `mapTo(true)` at the end of the pipe to achieve this. Why? To avoid confusion by someone using the point-in-time data instead of Query. **The purpose of your Resolve is then to ensure the data is ready** and not to actually return it. – Simon_Weaver Aug 13 '19 at 05:00