我想从基本的angular-redux todo应用程序中的服务器获取json数据。另外请解释数据流如何从商店发生。如果你可以在这个问题上引用任何博客,那就太棒了。我无法从ng2-redux或ngrx中获得很多意义。请提前告诉你。
答案 0 :(得分:0)
您应该在Middleware中进行API调用。阅读这个book,它是免费的,它将清除你的大部分疑虑,它在我开始学习时为我做了。
答案 1 :(得分:0)
您应该使用像Epic这样的中间件来进行API调用(称为副作用)。
让我们考虑一个您需要从服务器获取待办事项的待办事项应用程序示例:
const BASE_URL = "https://some-server/api/";
@Injectable()
export class TodoEpics implements EpicMiddleware {
constructor(private httpService: HttpClient) {
}
@dispatch()
startLoading() {
return changeTodoStatus("loading");
}
getTodosEpic = (action$: ActionsObservable<GetTodosAction>, state$: StateObservable<AppState>): Observable<Action> => {
return action$.pipe(
ofType(todoConstants.GET_TODOS),
tap((action) => this.startLoading()),
mergeMap(action => this.httpService.get<GetTodosResponse>(`${BASE_URL}/todos`).pipe(
map((response) => getTodosSucceeded(response.items)),
catchError(error => of(getTodosFailed(error)))
))
);
}
getEpics(): Epic[] {
return [
this.getTodosEpic
];
}
}
以及在主商店模块中:
import { NgModule } from '@angular/core';
import { NgReduxModule, NgRedux, DevToolsExtension } from '@angular-redux/store';
import { createLogger } from 'redux-logger';
import { AppState } from './models';
import { rootReducer } from './reducers';
import { TodoEpics } from "../todo-list/todo-list-state-management/epics";
import { combineEpics, createEpicMiddleware } from "redux-observable";
import { environment } from "../../environments/environment";
const epicMiddleware = createEpicMiddleware();
@NgModule({
imports: [NgReduxModule],
providers: [
TodoEpics
]
})
export class StoreModule {
constructor(private store: NgRedux<AppState>, private todoEpics: TodoEpics) {
const rootEpic = combineEpics(
...this.todoEpics.getEpics()
);
const middelwares = [epicMiddleware]
const devMiddelwares = [...middelwares, createLogger()];
const prodMiddelwares = [...middelwares];
store.configureStore(
rootReducer,
environment.production ? prodMiddelwares : devMiddelwares);
epicMiddleware.run(rootEpic)
}
}
可以在此处找到完整的示例:Todo app using angular-redux, redux-observable and epics