要解决Angular 8中使用ngRx/store从reducer获取的结果在异步(html)中未更新UI的问题,可以按照以下步骤进行:
确保已经正确配置了ngRx/store和相关的reducers、actions和effects。
在组件中订阅ngRx/store中的状态,以便在状态发生变化时更新UI。可以使用select
操作符来获取状态的值。
import { Component, OnInit } from '@angular/core';
import { Store, select } from '@ngrx/store';
@Component({
selector: 'app-example',
template: `
{{ data }}
`
})
export class ExampleComponent implements OnInit {
data: any;
constructor(private store: Store) {}
ngOnInit() {
this.store.pipe(select('reducerName')).subscribe((state) => {
this.data = state.data;
});
}
}
在上面的代码中,reducerName
是你的reducer的名称,data
是你想要获取的状态的属性。
确保在异步操作中正确地触发了相关的actions和effects,并且在reducer中更新了相应的状态。
确保在异步操作完成后,通过dispatch一个action来触发状态的更新。可以在effect中使用tap
操作符来处理异步操作完成后的逻辑。
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { map, mergeMap, catchError, tap } from 'rxjs/operators';
@Injectable()
export class ExampleEffects {
exampleEffect$ = createEffect(() =>
this.actions$.pipe(
ofType('EXAMPLE_ACTION'),
mergeMap(() =>
// 这里模拟一个异步操作,如发起HTTP请求
this.apiService.getData().pipe(
map((response) => ({
type: 'EXAMPLE_ACTION_SUCCESS',
payload: response
})),
catchError((error) => of({ type: 'EXAMPLE_ACTION_ERROR', payload: error }))
)
),
tap(() => {
// 异步操作完成后,dispatch一个action来触发状态的更新
this.store.dispatch({ type: 'UPDATE_STATE' });
})
)
);
constructor(private actions$: Actions, private apiService: ApiService, private store: Store) {}
}
在上面的代码中,EXAMPLE_ACTION
是你的action的类型,EXAMPLE_ACTION_SUCCESS
和EXAMPLE_ACTION_ERROR
是异步操作成功和失败时的action类型。
通过以上步骤,你应该能够在Angular 8中使用ngRx/store从reducer获取的结果在异步(HTML)中更新UI。