【发布时间】:2020-06-10 00:06:22
【问题描述】:
我有一个 Angular 9 应用程序,在 HttpClient POST 请求后刷新我的页面时遇到了一些问题。
这是我的表单和表单组件:
<form #myForm="ngForm" (ngSubmit)="save(myForm)">
<button type="submit" class="btn btn-success submit-button">
Submit
</button>
</form>
----------------------------------------------------------
@Component({
selector: 'my-form',
templateUrl: './my-form.component.html',
})
export class MyFormComponent implements OnInit {
constructor(private apiService: APIService, private ngZone: NgZone, private router: Router) {}
ngOnInit() {}
save(myForm: NgForm) {
this.apiService.addSomething(myForm.value).subscribe((res) => {
// Not sure what to do here to get the page to reload.
});
}
}
我尝试过调用this.apiService.getSomething()(这是获取所有内容的 REST 端点)。我曾尝试做类似this.ngZone.run(() => this.router.navigate('/')) 之类的事情,我在 SO 上的另一个问题中看到过,但这也没有用。
任何帮助将不胜感激。
为了更好的衡量,这是我的 api 服务:
@Injectable({
providedIn: 'root',
})
export class APIService {
private SERVER_URL = 'http://localhost:8080';
constructor(private httpClient: HttpClient) {}
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
};
// Get all the things
public getAllThings() {
return this.httpClient.get(this.SERVER_URL + '/things').pipe(catchError(this.handleError));
}
// Add a thing
public addSomething(thing: ThingType) {
return this.httpClient
.post(this.SERVER_URL + '/things', submission, this.httpOptions)
.pipe(catchError(this.handleError));
}
}
编辑:我的目标是显示一条成功消息(可能在提交按钮附近),表明表单已提交并清除表单。
【问题讨论】:
-
您想清空表格吗?刷新页面的目的是什么?
-
是的,主要目的是显示表单已填写的“成功”消息并清除表单。我会修改我的问题以包含它。
标签: angular