使用 Angular ngrx 存储效果按 id 查询数据
Posted
技术标签:
【中文标题】使用 Angular ngrx 存储效果按 id 查询数据【英文标题】:Using angular ngrx store effects to query data by id 【发布时间】:2019-05-01 03:44:55 【问题描述】:我使用的是ngrx 6和angular 6,我的代码如下:
效果.ts
import * as fromProjectMemberActions from '../project-member/project-member.actions';
import * as fromProjectMemberGraphQL from '../../members/members.graphql';
@Effect(dispatch: false)
loadProjectMember$ = this.actions$.pipe(
ofType(fromProjectMemberActions.ProjectMemberActionTypes.GetProjectMembers),
tap(
action =>
this.apollo.watchQuery(
query: fromProjectMemberGraphQL.GET_ALL_PROJECT_MEMBERS,
variables:
projectID : // Project ID is needed
).valueChanges.subscribe((response: any) =>
console.log(response)
this.store.dispatch(
new fromProjectMemberActions.UpsertProjectMembers(
projectMembers: response.data.findAllProjectMember
)
)
this.store.dispatch(
new fromProjectMemberActions.DoneLoadingProjectMembers()
)
)
)
);
项目成员.actions.ts
export class GetProjectMembers implements Action
readonly type = ProjectMemberActionTypes.GetProjectMembers;
export class UpsertProjectMembers implements Action
readonly type = ProjectMemberActionTypes.UpsertProjectMembers;
constructor(public payload: projectMembers: ProjectMember[] )
members.graphql.ts
import gql from 'graphql-tag';
export const GET_ALL_PROJECT_MEMBERS = gql`
query getAllProjectMembers($projectID: Long!)
findAllProjectMembers(projectId: $projectID)
id
memberId
memberType
`;
给定的 graphql API 在 graphql playground 上如下所示
query
findAllProjectMembers(projectId: projectID)
id
memberId
memberType
如果将上面的projectID替换为数字,例如:2,它将成功查询数据
要在数字 1 上使用的项目 ID 的 url 通过以下 URL 传递
http://localhost/project-manager/view-project/2/members
我需要帮助来提取上面的项目 ID 并在效果文件中使用它来查询成员列表
【问题讨论】:
您在组件中调度操作 ofType(fromProjectMemberActions.ProjectMemberActionTypes.GetProjectMembers) 的位置。 ? 【参考方案1】:我会说。
//更新项目成员.actions.ts
export class GetProjectMembers implements Action
readonly type = ProjectMemberActionTypes.GetProjectMembers;
constructor(public payload: projectId: number )
//和更新效果
@Effect(dispatch: false)
loadProjectMember$ = this.actions$.pipe(
ofType(fromProjectMemberActions.ProjectMemberActionTypes.GetProjectMembers),
map((action: any) => action.payload),
tap(
payload =>
this.apollo.watchQuery(
query: fromProjectMemberGraphQL.GET_ALL_PROJECT_MEMBERS,
variables:
projectID : payload.projectId
).valueChanges.subscribe((response: any) =>
console.log(response)
this.store.dispatch(
new fromProjectMemberActions.UpsertProjectMembers(
projectMembers: response.data.findAllProjectMember
)
)
this.store.dispatch(
new fromProjectMemberActions.DoneLoadingProjectMembers()
)
)
)
);
// 可能在组件中或者你调度action的地方传递projectId
subscribe to router
this.store.dispatch(new GetProjectMembers( projectId )
【讨论】:
以上是关于使用 Angular ngrx 存储效果按 id 查询数据的主要内容,如果未能解决你的问题,请参考以下文章
在 angular/ngrx 应用程序中将状态保存到本地存储的逻辑的位置
在单元测试中使用参数模拟 ngrx 存储选择器(Angular)
Angular+ngrx:如何在路由器 url 遍历中保持存储状态?
发生未处理的异常:不支持:关键字“id”,使用“$id”作为模式 ID - Angular 13 中的“ng add @ngrx/store”