我try 在创建记录时通知用户操作的成功或失败
为此,我准备了以下内容:
Post.actions.ts
export const PostActions = createActionGroup({
source: 'Create post component',
events: {
'Create post': props<{ payload: CreatePostModel }>(),
'Successful post creation': emptyProps(),
'Failed post creation': props<{ payload: any }>(),
},
});
Post.effects.ts
@Injectable()
export class ContentEffects {
addContent$ = createEffect(() =>
this.actions$.pipe(
ofType(PostActions.createPost),
exhaustMap((action) =>
this.postService.save(action.payload).pipe(
map(
(payload) => PostActions.successfulPostCreation(),
catchError((error) =>
of(PostActions.failedPostCreation({ payload: error }))
)
)
)
)
)
);
constructor(
private readonly postService: PostService,
private readonly actions$: Actions
) {}
}
Post.reducer.ts
export interface PostState {
success: string;
error: any;
}
export const initialState: PostState = { success: '', error: undefined };
export const postReducer = createReducer(
initialState,
on(PostActions.successfulPostCreation, (state) => ({
...state,
success: 'shared.success',
error: undefined,
})),
on(PostActions.failedPostCreation, (state, { payload }) => ({
...state,
success: '',
error: payload,
}))
);
Post.selectors.ts
export const selectSuccess = createFeatureSelector<string>('success');
export const selectError = createFeatureSelector<any>('error');
Create-post.component.ts
@Component({
selector: 'app-post-create',
templateUrl: './post-create.component.html',
styleUrls: ['./post-create.component.scss'],
})
export class PostCreateComponent implements OnInit {
@ViewChild('form', { static: false }) form: NgForm;
success$: Observable<string>;
error$: Observable<any>;
constructor(
private readonly notificationService: NotificationService,
private readonly store: Store)
{
this.success$ = this.store.select(selectSuccess);
this.error$ = this.store.select(selectError);
}
ngOnInit(): void {
this.success$.subscribe({
next: (value) => {
this.form.resetForm();
this.formGroup.reset();
this.notificationService.success(value);
},
});
this.error$.subscribe({
next: (value) => this.notificationService.error(value),
});
}
submit() {
const model { ... }
this.store.dispatch(PostActions.createPost({ payload: model }));
}
}
流程是否成功,我可以验证记录是否已创建,我还可以确认状态的Success属性是否已创建,但不会显示成功通知消息.调试中,我成功地验证了订阅从未被调用
我希望在成功完成这一进程后调用它.
this.success$.subscribe({
next: (value) => {
this.form.resetForm();
this.formGroup.reset();
this.notificationService.success(value);
},
});
没有调用订阅的原因是什么?
提前谢谢你