我正在开发一个涉及编辑和更新帖子的 Angular 应用程序。当用户离开编辑帖子页面并返回时,数据和成功/错误状态将被保留。我想在用户返回页面时将成功/错误状态消息设置为 null,以确保他们看到最新的帖子内容,而不会看到以前提交的任何成功或错误消息。我怎样才能实现这个目标?
供参考的代码片段:
EditPostPageComponent - 编辑帖子页面的组件。 包含表单并订阅成功和错误消息的状态。
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { UpdatePostData } from '@client-app/user/models';
import * as fromUser from '@client-app/user/reducers';
import { PostsPageActions } from '@client-app/user/actions';
@Component({
selector: 'app-edit-post-page',
template: `
<app-edit-post-form
(submitted)="onSubmit($event)"
[pending]="(pending$ | async)!"
[errorMessage]="error$ | async"
[successMessage]="success$ | async"
></app-edit-post-form>
`,
styles: [],
})
export class EditPostPageComponent implements OnInit {
pending$ = this.store.select(fromUser.selectUpdatePostPagePending);
error$ = this.store.select(fromUser.selectUpdatePostPageError);
success$ = this.store.select(fromUser.selectUpdateSuccessMsg);
constructor(private store: Store) {}
onSubmit(event: { postId: string; formData: UpdatePostData }) {
this.store.dispatch(
PostsPageActions.updatePost({
postId: event.postId,
updatePostData: event.formData,
})
);
}
ngOnInit(): void {}
}
EditPostFormComponent - 编辑帖子表单的组件。订阅 post$ observable 并相应地设置表单值。
import {
Component,
Input,
Output,
EventEmitter,
OnDestroy,
} from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { Store } from '@ngrx/store';
import { Observable, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import * as fromUser from '@client-app/user/reducers';
import { Post, UpdatePostData } from '@client-app/user/models';
import { UserPostPageActions } from '@client-app/user/actions';
@Component({
selector: 'app-edit-post-form',
template: `
<mat-card>
<mat-card-title>Edit post</mat-card-title>
<mat-card-content>
<form [formGroup]="form" (ngSubmit)="submit()">
<p>
<mat-form-field>
<textarea
matInput
placeholder="Description"
formControlName="description"
></textarea>
</mat-form-field>
</p>
<p>
<mat-form-field>
<input
type="text"
matInput
placeholder="Location"
formControlName="location"
/>
</mat-form-field>
</p>
<p>
<mat-form-field>
<input
type="text"
matInput
placeholder="Mood"
formControlName="mood"
/>
</mat-form-field>
</p>
<p>
<mat-form-field>
<input
type="text"
matInput
placeholder="Weather"
formControlName="weather"
/>
</mat-form-field>
</p>
<p>
<mat-checkbox formControlName="isPublic">Public</mat-checkbox>
</p>
<p
*ngIf="errorMessage || successMessage"
class="edit-post-message"
[ngClass]="{
'edit-post-error': errorMessage,
'edit-post-success': successMessage
}"
>
{{ errorMessage || successMessage }}
</p>
<div class="edit-post-buttons">
<button
type="submit"
mat-raised-button
color="primary"
[disabled]="disabled"
>
Save
</button>
</div>
</form>
</mat-card-content>
</mat-card>
`,
styles: [
`
:host {
display: flex;
justify-content: center;
margin: 4.5rem 0;
}
mat-card-title {
text-align: center;
margin: 1rem 0;
}
mat-card-content {
min-width: 300px;
}
mat-form-field {
width: 100%;
}
.edit-post-message {
padding: 1rem;
color: white;
}
.edit-post-error {
background-color: red;
}
.edit-post-success {
background-color: green;
}
.edit-post-buttons {
display: flex;
justify-content: center;
}
`,
],
})
export class EditPostFormComponent implements OnDestroy {
@Input() pending!: boolean;
@Input() errorMessage!: string | null;
@Input() successMessage!: string | null;
@Output() submitted = new EventEmitter<{
postId: string;
formData: UpdatePostData;
}>();
form: FormGroup = new FormGroup({
description: new FormControl(''),
location: new FormControl(''),
mood: new FormControl(''),
weather: new FormControl(''),
isPublic: new FormControl(true),
});
private postId!: string;
private destroy$ = new Subject<void>();
post$: Observable<Post>;
disabled: boolean = false;
constructor(private store: Store, private route: ActivatedRoute) {
this.post$ = store.select(fromUser.selectUserPost);
}
ngOnInit(): void {
// Accessing URL parameters
this.route.params.subscribe((params) => {
this.postId = params['postId'];
});
this.store.dispatch(UserPostPageActions.enter({ postId: this.postId }));
// Subscribe to the post$ observable and set form values when data is received
this.post$.pipe(takeUntil(this.destroy$)).subscribe((post) => {
if (post) {
this.form.patchValue({
description: post.description,
location: post.location,
mood: post.mood,
weather: post.weather,
isPublic: post.isPublic,
});
}
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
submit() {
if (this.form.valid) {
const formData: UpdatePostData = this.form.value;
this.submitted.emit({ postId: this.postId, formData });
this.form.reset();
this.disabled = true;
}
}
// Disable/Enable form when 'pending' changes
ngOnChanges(): void {
if (this.pending) {
this.form.disable();
} else {
this.form.enable();
}
}
}
您需要创建一个操作来将状态重置为其初始值。 可以在打开表单或关闭表单时调度此操作。
附带说明:也许这个状态不需要存储在全局存储中。将状态保留在组件存储中是可以的。