X Tutup
Skip to content

Commit 74bae91

Browse files
Rough but working example of displaying server-side validation errors. Needs cleaner patterns/APIs.
1 parent 7ac0727 commit 74bae91

File tree

1 file changed

+28
-2
lines changed
  • samples/angular/MusicStore/wwwroot/ng-app/components/admin/album-edit

1 file changed

+28
-2
lines changed

samples/angular/MusicStore/wwwroot/ng-app/components/admin/album-edit/album-edit.ts

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import { Http, HTTP_BINDINGS, Headers } from 'angular2/http';
55
import { AlbumDeletePrompt } from '../album-delete-prompt/album-delete-prompt';
66
import { FormField } from '../form-field/form-field';
77

8+
const ContentTypeJson = 'application/json';
9+
810
@ng.Component({
911
selector: 'album-edit'
1012
})
@@ -63,10 +65,29 @@ export class AlbumEdit {
6365
var albumId = this.originalAlbum.AlbumId;
6466
(<any>window).fetch(`/api/albums/${ albumId }/update`, {
6567
method: 'put',
66-
headers: { 'Content-Type': 'application/json' },
68+
headers: { 'Content-Type': ContentTypeJson },
6769
body: JSON.stringify(this.form.value)
6870
}).then(response => {
69-
console.log(response);
71+
if (response.status >= 200 && response.status < 300) {
72+
// TODO: Display success message
73+
} else {
74+
if (response.headers.get('Content-Type').indexOf(ContentTypeJson) === 0) {
75+
return response.json().then((responseJson: ValidationResponse) => {
76+
Object.keys(responseJson.ModelErrors).forEach(key => {
77+
responseJson.ModelErrors[key].forEach(errorMessage => {
78+
// TODO: There has to be a better API for this
79+
if (!this.form.controls[key].errors) {
80+
(<any>this.form.controls[key])._errors = {};
81+
}
82+
83+
this.form.controls[key].errors[errorMessage] = true;
84+
});
85+
});
86+
});
87+
} else {
88+
// TODO: Display generic 'unknown error'
89+
}
90+
}
7091
});
7192
}
7293
}
@@ -75,3 +96,8 @@ export class AlbumEdit {
7596
return /^\d+\.\d+$/.test(control.value) ? null : { Price: true };
7697
}
7798
}
99+
100+
interface ValidationResponse {
101+
Message: string;
102+
ModelErrors: { [key: string]: string[] };
103+
}

0 commit comments

Comments
 (0)
X Tutup