我正在尝试使用httpClient
inAngular
进行 API 调用。这是我进行 api 调用的代码。
这是我的httpPost
方法authService
:
this.authService.httpPost("/api/Users/requestNew", payload).subscribe(
(data) => {
console.log(data);
this.inputForm.reset();
},
(error) => {
let errorMessage = "Ooooops. An error occured. Please refresh and try again.";
}
);
auth.service.ts
constructor(
private http: HttpClient,
private dataService: DataService
) {}
httpPost(url, payload) {
return this.http.post(
this.url_base + ":" + this.port + url,
payload, {
headers: new HttpHeaders({
"Content-Type": "application/json",
Authorization: localStorage.getItem("id_token")
})
}
);
}
现在,在有效负载中,我故意遗漏了一个字段,结果服务器抛出了一个错误。这是我从服务器得到的错误:
http://192.168.0.15:3000/api/Users/requestNew 450 (unknown)
来自服务器的响应:
{"error":{"statusCode":"450","message":"Duration is not set.","code":"MISSING_FIELD"}}
现在我面临的问题是我的页面会自动刷新。这是我原来的 url: http://localhost:4200/user/new
,在 api 调用之后,页面会用这个新的 url 刷新http://localhost:4200/user/new?
。添加了一个额外的问号,我不确定为什么页面会刷新。它不应该被刷新,因为在我的逻辑中没有我写过的地方。
编辑
我有一个formGroup
inputForm: FormGroup;
durationsControl: FormControl = new FormControl(null, [
Validators.required
]);
ngOnInit(){
this.inputForm = new FormGroup({
duration: this.durationsControl,
//more controls
});
}
在更改下拉列表时,我将删除此控件:
valueCHanged(e) {
const type = e.value;
if (type === "One") {
this.durationDiv.nativeElement.style.display = "none";
this.inputForm.removeControl("duration");
} else {
this.durationDiv.nativeElement.style.display = "block";
this.inputForm.addControl("duration", this.durationsControl);
}
}
如果我不删除持续时间控制(this.inputForm.removeControl("duration");)
,那么它会完美运行。这种变化如何导致页面刷新?
Edit1
我duration
从以下位置删除了控件ngOnInit()
:
ngOnInit(){
this.inputForm = new FormGroup({
// duration: this.durationsControl, ---> removed this
//more controls
});
}
现在它工作正常,页面没有刷新。但我仍然无法弄清楚原因。