-
Notifications
You must be signed in to change notification settings - Fork 0
/
user-profile.component.ts
208 lines (176 loc) · 6.34 KB
/
user-profile.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import { Component, inject, OnInit } from '@angular/core';
import { CommonModule, NgOptimizedImage } from "@angular/common";
import { FormBuilder, FormControl, ReactiveFormsModule, Validators } from "@angular/forms";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatInputModule } from "@angular/material/input";
import { MatButtonModule } from "@angular/material/button";
import { HttpClient } from "@angular/common/http";
import { finalize } from "rxjs";
import { isEqual, pick } from "lodash-es";
import { NotificationService } from "../services/notification.service";
import { MatProgressBarModule } from "@angular/material/progress-bar";
import { FieldValidationErrorMessages } from "../shared/types/validation-errors";
import { ValidationErrorDirective } from "../shared/directives/validation-error.directive";
import { ImageFormControlComponent } from "../shared/components/image-form-control/image-form-control.component";
import { tapValidationErrors } from "../shared/rxjs-operators/tap-validation-errors";
import { tapUploadProgress } from "../shared/rxjs-operators/tap-upload-progress";
import { tapResponseData } from "../shared/rxjs-operators/tap-response-data";
import { ApiSuccessResponse, ApiValidationErrorResponse } from "../shared/types/http-response";
import { tapError } from "../shared/rxjs-operators/tap-error";
interface UserProfile {
id: number;
name: string;
email: string;
address: string;
avatar: string;
}
type UserDataResponse = ApiSuccessResponse<UserProfile>;
type UserProfileForm = Pick<UserProfile, "name" | "email" | "address" | "avatar">
@Component({
selector: 'app-user-profile',
standalone: true,
imports: [CommonModule, ReactiveFormsModule, MatFormFieldModule, MatInputModule, MatButtonModule, NgOptimizedImage, MatProgressBarModule, ValidationErrorDirective, ImageFormControlComponent],
templateUrl: './user-profile.component.html',
styleUrl: './user-profile.component.css'
})
export class UserProfileComponent implements OnInit {
private httpClient = inject(HttpClient);
private notification = inject(NotificationService);
protected form = inject(FormBuilder).group({
name: new FormControl('', [Validators.required]),
email: new FormControl('', [Validators.required, Validators.email]),
address: new FormControl('', [Validators.required]),
avatar: new FormControl<string|Blob>('')
});
protected errorMessages: FieldValidationErrorMessages = {
name: {
required: 'Please fill in the name'
},
email: {
required: 'Please fill in the email'
},
address: {
required: 'Please fill in the address'
},
};
private userData: UserProfile | null = null;
protected isLoadRequestInProgress = false;
protected hasLoadingError = false;
protected isSaveRequestInProgress = false;
protected uploadProgress: number = 0;
protected get isSaveButtonDisabled() {
return !this.form.valid || this.isFormPristine || this.isSaveRequestInProgress;
}
protected get isResetButtonDisabled() {
return this.isFormPristine || this.isSaveRequestInProgress;
}
/**
* Checks if the form value reflects the last value received from the backend
*/
private get isFormPristine(): boolean {
return Boolean(this.userData)
&& Boolean(this.form.value)
&& isEqual(
this.form.value,
pick(this.userData, Object.keys(this.form.value))
)
}
ngOnInit() {
this.loadUserData();
}
protected loadUserData() {
// set the loading flag when the request is initiated
this.isLoadRequestInProgress = true;
this.getUserData$()
.pipe(
finalize(() => {
// clear the loading flag when the request completes
this.isLoadRequestInProgress = false;
}),
tapResponseData(data => {
// clear the loading error flag
this.hasLoadingError = false;
// store the user data
this.userData = data
// display the user data in the form
this.updateForm(this.userData);
}),
tapError(() => {
// set the loading error flag
this.hasLoadingError = true;
})
)
.subscribe()
}
private getUserData$() {
return this.httpClient.get<UserDataResponse>(
`http://localhost:3000/users/1`
);
}
private updateForm(userData: UserProfile) {
this.form.reset(pick(userData, Object.keys(this.form.value)) as UserProfileForm)
}
protected saveUserData() {
// set the saving flag
this.isSaveRequestInProgress = true;
this.saveUserData$()
.pipe(
finalize(() => {
// clear the saving flag
this.isSaveRequestInProgress = false;
// reset the progress
this.uploadProgress = 0;
}),
tapResponseData(data => {
// store the user data
this.userData = data
// update the form with the values received from the server
this.restoreForm();
// display a success notification
this.notification.display('The profile was successfully saved');
}),
// handle server-side validation errors
tapValidationErrors(errors => {
this.setFormErrors(errors.error)
}),
tapUploadProgress(progress => {
this.uploadProgress = progress;
}),
tapError(() => {
// display a notification when other errors occur
this.notification.display('An unexpected error has occurred. Please try again later.')
})
)
.subscribe()
}
private saveUserData$() {
return this.httpClient.put<UserDataResponse>(
`http://localhost:3000/users/1`,
this.getFormData(),
{
reportProgress: true,
observe: 'events',
})
}
private setFormErrors(errorResponse: ApiValidationErrorResponse | null | undefined) {
if (!errorResponse || !errorResponse.errors) {
this.form.setErrors(null);
return;
}
errorResponse.errors.forEach(error => {
this.form.get(error.field)?.setErrors({
[error.code]: error.message
})
})
}
protected restoreForm() {
this.userData && this.updateForm(this.userData);
}
private getFormData() {
const formData = new FormData();
Object.entries(this.form.value).forEach(([fieldName, value]) => {
formData.append(fieldName, value as string | Blob);
})
return formData;
}
}