Дело:
Приложение Angular 6 с магазином NGRX. В одном из компонентов приложение запрашивает данные о погоде из внешнего API и сохраняет их в хранилище. Что мне нравится делать, так это запрашивать данные из API только в том случае, если они недопустимы (свойство dt
в формате отметок времени UNIX имеет возраст 1 час) или их нет в хранилище. Я хотел бы, чтобы эта логика действовала.
Мой класс эффектов:
@Injectable()
export class WeatherEffects {
@Effect()
getWeather$: Observable<Action> = this.actions$
.ofType(weatherActions.GET)
.pipe(
switchMap(() =>
this.weatherService.getWeather().pipe(
map(data => ({
type: weatherActions.GET_WEATHER_SUCCESS,
payload: data
}))
)
)
);
constructor(
private weatherService: WeatherService,
private actions$: Actions,
private store: Store<fromStore.State>
) {}
}
Разбавление:
export function weatherReducer(state: WeatherResponse, action: Action) {
switch (action.type) {
case WeatherActions.GET:
return { ...state, loading: true, isQueried: true };
case WeatherActions.GET_WEATHER_SUCCESS:
return { ...state, ...action.payload, loading: false, isQueried: true };
default:
return { ...state, isQueried: false };
}
}
Здесь модель расширена до дополнительного поля isQueried
, установленного при запросе данных.
Часть модели погоды:
export interface WeatherResponse {
coord: Coord;
weather: Weather[];
base: string;
main: Main;
visibility: number;
wind: Wind;
clouds: Clouds;
dt: number;
sys: Sys;
id: number;
name: string;
cod: number;
}
In dt
- это отметка времени UNIX при запросе данных.
Ngrx 6.1.0
rxjs 6.0.0
Угловой 6.1.0