【问题标题】:Angular 9 - How to refresh form page after HttpClient POST?Angular 9 - 如何在 HttpClient POST 后刷新表单页面?
【发布时间】: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(() =&gt; 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


【解决方案1】:

要清除表单,请使用以下命令:

myForm.reset()

为显示成功消息创建一个变量,并在模板中添加一个条件元素。

isSuccess = false;

save(myForm: NgForm) {
   this.apiService.addSomething(myForm.value).subscribe((res) => {
       form.reset();
       this.isSuccess = true;
   });
}

模板:

<p *ngIf="isSuccess">Successful</p>

【讨论】:

  • 这是我需要的。谢谢!
【解决方案2】:

你的this.router.navigate(['']) 应该没问题。

但 Angular 会禁用同一网址上的导航。

您在app-routing.module.ts 中启用此功能:

@NgModule({
  imports: [RouterModule.forRoot(routes, {
    onSameUrlNavigation: 'reload',
  })],
  exports: [RouterModule]
})

【讨论】:

  • 这很有帮助,因为我有另一个问题可以使用它来解决。
猜你喜欢
  • 2019-02-06
  • 2017-11-22
  • 2020-06-27
  • 1970-01-01
  • 2023-01-26
  • 2018-09-27
  • 1970-01-01
  • 2013-09-21
  • 1970-01-01
相关资源
最近更新 更多