接收来自action ngxs的HTTP响应可以通过以下步骤实现:
FetchDataAction
的Action。responseData
,用于保存响应数据。FetchDataAction
的HTTP响应。在Action处理器中,将接收到的响应数据保存到State的responseData
属性中。Select
装饰器订阅State中的responseData
属性。这样,当HTTP响应更新时,组件将自动接收到最新的响应数据。以下是一个示例代码,演示如何在NGXS中接收来自Action的HTTP响应:
// fetch-data.action.ts
import { HttpClient } from '@angular/common/http';
import { Action, State, StateContext } from '@ngxs/store';
import { tap } from 'rxjs/operators';
export class FetchDataAction {
static readonly type = '[Data] Fetch';
constructor(public payload: string) {}
}
export interface DataStateModel {
responseData: any;
}
@State<DataStateModel>({
name: 'data',
defaults: {
responseData: null
}
})
export class DataState {
constructor(private http: HttpClient) {}
@Action(FetchDataAction)
fetchData(ctx: StateContext<DataStateModel>, action: FetchDataAction) {
return this.http.get(action.payload).pipe(
tap((response: any) => {
ctx.patchState({
responseData: response
});
})
);
}
}
// data.component.ts
import { Component, OnInit } from '@angular/core';
import { Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { FetchDataAction, DataState, DataStateModel } from './fetch-data.action';
@Component({
selector: 'app-data',
template: `
<div *ngIf="responseData$ | async as responseData">
<!-- Display responseData in the component -->
{{ responseData | json }}
</div>
`
})
export class DataComponent implements OnInit {
@Select(DataState)
responseData$: Observable<DataStateModel>;
constructor(private store: Store) {}
ngOnInit() {
// Dispatch FetchDataAction to initiate HTTP request
this.store.dispatch(new FetchDataAction('https://api.example.com/data'));
}
}
在上述示例中,FetchDataAction
用于发送HTTP请求,并将响应数据保存到DataState
的responseData
属性中。DataComponent
订阅DataState
中的responseData$
属性,以便在组件中显示最新的响应数据。
请注意,示例中的代码仅用于演示目的,实际应用中可能需要根据具体需求进行适当的修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云