【发布时间】:2021-06-12 11:27:17
【问题描述】:
我第一次尝试使用响应式表单应用 Angular HTTP put。我的问题是,当我应用以下代码时,出现 404 错误。该错误指示未找到服务器 URL(XHR PUT http://localhost:3000/feedback)。当我单独使用 URL 时,它通常会带来数据,来自 JSON 服务器的消息是 200 (GET /feedback 200 28.207 ms - 200)。这意味着网址没有问题!但是,在 HTTP put 的情况下得到 404
JSON 服务器结构(我需要放入“反馈”:[])
{
"dishes": [ ...
],
"promotions": [ ...
],
"leaders": [ ...
],
"feedback": [
{
"firstname": "Ali",
"lastname": "Sleam",
"telnum": "123123123",
"email": "Ali@gmail.com",
"agree": false,
"contacttype": "None",
"message": "This is my message"
}
]
}
feedback.service.ts
...
export class FeedbackService {
constructor(private http: HttpClient,
private processHTTPMsgService: ProcessHTTPMsgService) { }
submitFeedback(feedBack: Feedback): Observable<Feedback> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.put<Feedback>('http://localhost:3000/feedback', feedBack, httpOptions);
}
}
组件.ts
...
feedbackForm: FormGroup;
feedback: Feedback;
contactType = ContactType;
...
constructor(private fb: FormBuilder,private feedbackService: FeedbackService) {
this.createForm();
}
...
createForm() {
this.feedbackForm = this.fb.group({
firstname: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(25)] ],
lastname: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(25)] ],
telnum: ['', [Validators.required, Validators.pattern] ],
email: ['', [Validators.required, Validators.email] ],
agree: false,
contacttype: 'None',
message: ''
});
}
...
onSubmit() {
this.feedback = this.feedbackForm.value;
this.feedbackService.submitFeedback(this.feedback) // <--- add to the server (put)
.subscribe(feedback => { this.feedback = feedback; },
errmess => { this.feedback = null; this.errMess = <any>errmess; });
}
component.html
<form novalidate [formGroup]="feedbackForm" #fform="ngForm" (ngSubmit)="onSubmit()">
...
<button type="submit" mat-button class="background-primary text-floral-white">Submit</button>
</form>
更新——反馈类
export class Feedback {
firstname: string;
lastname: string;
telnum: number;
email: string;
agree: boolean;
contacttype: string;
message: string;
};
export const ContactType = ['None', 'Tel', 'Email'];
【问题讨论】:
标签: angular angular-reactive-forms angular-http json-server