从具有 http 服务的操作 (NGXS) 返回值



有没有其他更干净的方法可以通过操作(NGXS(从http服务返回值?还是我们应该始终更新"结果"状态,以便在您返回时进行咨询?

下面的代码有效,非常接近文档。 但是,对我来说似乎不是很干净。

export class DeleteAction {
static readonly type = '[Test] Delete';
constructor(public id: number) { }
}
@State<TestStateModel>({
name: 'test',
defaults: {
result: null
}
})
export class TestState {
constructor(
private testService: TestService) {
}
@Selector()
static getResult(state: TestStateModel): NotificationResult {
return state.result;
}
@Action(DeleteAction)
public delete({ patchState }: StateContext<TestStateModel>, { id }: DeleteAction) {
return this.testService
.delete(id)
.pipe(
take(1),
tap(result => {
patchState({ result });
})
);
}
@Component({
templateUrl: './test.component.html'
})
export class TestComponent {
@Select(SubjectState.getResult) result$;
private delete(id: number): void {
this.isLoading = true;
this.store.dispatch(new DeleteAction(id))
.pipe(withLatestFrom(this.result$))
.subscribe(([_, r]) => {
const result = r as NotificationResult;
if (result.isValid) {
// ...
} else {
// ...
}
this.isLoading = false;
});
}
}
export interface NotificationResult {
isValid: boolean;
messages: NotificationMessage[];
}

由于除了调用"Delete"方法之外,我不会使用"结果",因此似乎没有必要为此目的创建状态。

还有比这更优雅的方式吗?

不将查看删除结果链接到调度会更干净。而是当前使用删除方法的方法:

  1. 调度删除操作
  2. 等待操作完成
  3. 查看状态的最新值
  4. 对它做出反应

您可以:

  1. 让删除方法调度删除操作
  2. 订阅对$result的更改(例如,在 init 方法中(,并对获得的更改做出适当的反应

这对我来说似乎更干净。 思潮?

最新更新