【问题标题】:Nativescript Angular NGRX effect lose state when app is suspended (ios)应用程序暂停时 Nativescript Angular NGRX 效果丢失状态(ios)
【发布时间】:2020-08-15 10:12:01
【问题描述】:

我正在使用带有 Nativescript Angular 的 NGRX 来存储状态并从服务器获取数据。但是,每次如果我在应用程序从服务器获取数据时暂停应用程序(IOS),整个过程将停止并丢失其所有状态。当我打开并恢复应用程序时,没有返回任何数据。有什么方法可以解决吗?

流程如下:

component.ts(调用 NGRX 动作加载数据)->actions.ts(触发效果加载数据)->effects.ts(调用服务从服务器加载数据,如果应用程序被挂起,这将被取消在此过程中恢复)

组件.ts

this.store.dispatch(new DataActions.LoadData(this.pageNumber));

action.ts

export class LoadData implements Action {
readonly type = ActionTypes.LoadData;

constructor(
    public pageNumber: number) {
        console.log('load more data action'); //This is seen in the log
    }
}

效果.ts

@Effect()
    loadData$: Observable<Action> = this.actions$.pipe(
        ofType<DataActions.LoadData>(
            DataActions.ActionTypes.LoadData
        ),
        mergeMap((action: DataActions.LoadData) => 
            this.dataService.getData(action.pageNumber).pipe(
                map((data: any) => {
                    console.log(data.result); //This is not seen in the log when app is suspend
                    return new DataActions.LoadDataSuccess(data.result);
                }),
                catchError(err => of(new DataActions.LoadDataFailed(err)))
            )
        )
    );

dataService.service.ts

getData(pageNumber: number): Observable<PaginatedResult<Data[]>> {
const paginatedResult: PaginatedResult<Data[]> = new PaginatedResult<Data[]>();
let queryString = '?';

if (pageNumber != null) {
  queryString += 'pageNumber=' + pageNumber ;
}

return this.http
.get(this.baseUrl + queryString, {observe: 'response'})
  .pipe(
      map((response: any) => {
        paginatedResult.result = response.body;

        console.log(paginatedResult.result); //This is not seen in the log if app suspend

        return paginatedResult;
      })
  );

}

【问题讨论】:

标签: angular nativescript ngrx angular2-nativescript


【解决方案1】:

当我需要保留一些 NGRX 状态时,我经常使用ngrx-store-localstorage

它可以在您的 Angular 模块中轻松配置:

import { StoreModule, Action, ActionReducer, MetaReducer } from '@ngrx/store';

import { localStorageSync } from 'ngrx-store-localstorage';

const STORE_KEYS_TO_PERSIST = [
  'stateKey1',
  'stateKey2'
];

export function localStorageSyncReducer(reducer: ActionReducer<YourAppState>): ActionReducer<YourAppState> {
  return localStorageSync({
    keys: STORE_KEYS_TO_PERSIST,
    rehydrate: true,
  })(reducer);
}

export const metaReducers: Array<MetaReducer<YourAppState, Action>> = [localStorageSyncReducer];

@NgModule({
  imports: [
    ...
    StoreModule.forFeature('your-app', reducers, {
      metaReducers
    }),
    ...
  ],

您只需要配置您要同步的存储切片(在示例中为STORE_KEYS_TO_PERSIST),库将为您处理存储数据同步。

请注意,我从未在基于移动的 Angular 应用程序中测试过它,尽管我认为它必须开箱即用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 2018-07-11
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多