如果数据未处于状态或无效,则查询

时间:2018-09-01 11:59:19

标签: angular rxjs ngrx

案子: 带有NGRX存储的Angular 6应用程序。在组件应用程序之一中,从外部API查询天气数据并将其保存在商店中。我想做的是仅在API数据无效(UNIX时间戳格式的dt属性存在1小时)或存储中不存在时才从API查询数据。我希望这种逻辑有效。

我的效果类:

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

dt中是查询数据时的UNIX时间戳。

Ngrx 6.1.0 rxjs 6.0.0 角度6.1.0

0 个答案:

没有答案