My current project involves working with NGRX for State Management in Angular 11.
On component load, I am displaying a list of tenants. To achieve this, I'm utilizing NGRX effects to make an HTTP request through a service.
This is the NGRX effect implementation:
@Injectable()
export class TenantsListEffects {
constructor(private actions$: Actions, private tenantListService: TenantAdministrationService) { }
loadTenants$ = createEffect(() => this.actions$.pipe(
ofType(TenantsListActions.TenantsListActionTypes.LoadTenantsLists),
switchMap(((action) => this.tenantListService.getAllTenantsUsingGET().pipe(
map(tenants => { return new TenantsListActions.LoadTenantsListsSuccess({ data: tenants }) }),
catchError(err => of(new TenantsListActions.LoadTenantsListsFailure({ error: err })))
)
))
))
}
Here is my tenantList.reducer.ts file:
export const tenantsListFeatureKey = 'tenantsListState';
export interface tenantsListState {
tenants: DisplayNameToTenantMappingResponse[],
loading: boolean,
error: string
}
export const initialState: tenantsListState = {
tenants: [],
loading: false,
error: ''
};
export function reducer(state = initialState, action: TenantsListActions): tenantsListState {
switch (action.type) {
case TenantsListActionTypes.LoadTenantsLists:
return {
...state,
loading: true
}
case TenantsListActionTypes.LoadTenantsListsSuccess:
return {
...state,
tenants: action.payload.data,
loading:false,
error: null
}
case TenantsListActionTypes.LoadTenantsListsFailure:
return {
...state,
error: action.payload.error,
loading: false
}
default:
return state;
}
}
And here is my selector:
const getTenantsListState = createFeatureSelector<tenantsListState>('tenantsListState');
export const getTenants = createSelector(
getTenantsListState,
state => state.tenants
)
export const getError = createSelector(
getTenantsListState,
state => state.error
)
Lastly, here is the service implementation:
@Injectable({
providedIn: 'root'
})
export class TenantAdministrationService {
public basePath: string ='';
constructor(private basePathService: BasePathService,private http: HttpClient) {
this.basePath = this.basePathService.selectEnv();
}
public getAllTenantsUsingGET():Observable<DisplayNameToTenantMappingResponse[]>{
let test = this.http.get<Array<DisplayNameToTenantMappingResponse>> (`${this.basePath}/admin/tenant`);
console.log('get list ', test);
return test
}
The issue I'm facing:
Initially, when I call the service, it doesn't return anything, resulting in nothing being stored in my NGRX store. However, after 2-3 seconds, the tenant list is returned and stored in the store as a state.
I attempted to make the service call method asynchronous, but it led to errors in the Effect.
If anyone has suggestions on how to handle this situation, please share your insights.