Effect:
getUserStatus$ = createEffect(() => this.actions$.pipe(
ofType(getUserStatus),
switchMap(_ => this.userApiService.getUserStatus().pipe(
map(userStatusApiResponse = > getUserStatusSuccess({
userStatusApiResponse
})),
catchError(error = > of(getUserStatusFailed({
error
})))))
));
Service:
public getUserStatus(): Observable<UserStatusApiResponse> {
return this.httpClient.get<CommonResponse<UserStatusApiResponse>> (`$ {
USER_STATUS_API
}`).pipe(
map(UserApiService.extractUserStatusApiResponse),
catchError(commonApiError)
);
}
Function for extracting GET response:
private static extractUserStatusApiResponse(response: CommonResponse<UserStatusApiResponse>): UserStatusApiResponse {
return response.data;
}
GET response
{
"httpStatus": 200,
"data": {
"necessaryField1: "f1",
"necessaryField2: "f2",
"unecessaryField3: "f3",
"unecessaryField4: "f4",
"arrayUsers": [
{
"A": {
"a1": "aaa",
"a2": "bbb",
"a3": 0
},
"B": {
"b1": "aaa",
"b2": "bbb",
"b3": 0
},
"C": {
"c1": "aaa",
"c2": "bbb",
"c3": 0
}
}
]
}
}
I need from above object below response model:
export interface UserStatusApiResponse {
"necessaryField1: string;
"necessaryField2: string;
"arrayUsers": ArrayUsers[]
}
Where from arrayUsers
I need only object A
and B
:
export interface ArrayUsers {
a: A;
b: B;
}
Reducer:
on(getUserStatusSuccess, (state, action) = > ({
...state,
error: null,
necessaryArray: {
necessaryField1: action.userStatusApiResponse.necessaryField1,
necessaryField2: action.userStatusApiResponse.necessaryField2,
},
arrayUsers: action.userStatusApiResponse.arrayUsers
})),
My problem:
Always in store I have all network responses, irrespective of UserStatusApiResponse
. Another field, which is not in UserStatusApiResponse
automatically expands the store.
How can I properly handle above problem? I would like to control the type of each object/array, but always in store I see all objects. Also with unecessaryField3
: f3
, unecessaryField4
: f4
and object C
...
Keep in mind that the typing is just for the compilation. It's compiled in JS and then, you haven't any type.
So if you want only particular fields, then you need to map your response to a new object with only the wanted keys.
So :
extractUserStatusApiResponse(response: ...){
return {
necessaryField1: response.data.necessaryField1,
necessaryField2: response.data.necessaryField2,
arrayUsers: response.data.arrayUsers.map(user => ({A:user.A, B:user.B}))
}
}