Saturday, May 5, 2018

Use a Singleton as a cache to determine if something has been put to the store or not in the Redux pattern inside of an Angular 4 application.

Here loadedWidgets, the array, is going to contain zero or one id, right? If it's zero then we are going to go out to an API endpoint to load data. Otherwise we will just let things be. This approach does not hand back data in either case. Instead we will let stuff in the store bleed up to the UI. All we are trying to do is determine if we need something new in the store.

@Injectable()
export class WidgetsEffect {
   constructor(private action: Actions, private service: WidgetsService) { }
   private loadedWidgets = [];
   
   @Effect()
   relationshipsHh$ = this.action.ofType("WidgetsRequest").switchMap((action:
         WidgetsRequestAction) => {
      return this.loadedWidgets.indexOf(action.uniqueId) > -1 ? from([]) :
            this.execute(action);
   });
   
   execute(action: WidgetsRequestAction) {
         const url = `/whatever/whatever/whatever/${action.uniqueId}`;
         const endpointConfiguration = new EndpointConfig(url, HTTP_VERBS.GET);
         return this.service.request<Array<Widget>>(endpointConfiguration).then(result => {
            this.loadedWidgets.push(action.uniqueId);
            return new WidgetsResponseAction(result.data);
         });
   }
}

 
 

One of the more confusing things about code like this the first time I saw it was the bit that reads from([]) which returns an empty Observable of sorts in order to conditionally sidestep the execute function.

No comments:

Post a Comment