【问题标题】:Angular 9: How to prevent reload page when change paramsAngular 9:更改参数时如何防止重新加载页面
【发布时间】:2021-07-12 09:26:13
【问题描述】:

我使用了 angular9 和 PathLocationStrategy

{provide: LocationStrategy, useClass: PathLocationStrategy},

我的问题是:
当我使用 form.submit() 将数据发布到后端时,后端将使用一些参数(例如:'/contacts?data=new')重定向到当前 URL。
我的网站将被重新加载。
我不想重新加载页面。我使用了参数订阅,但不起作用

this.route.queryParams.subscribe(params => { this.urlParams = 参数; });

在这种情况下如何防止重新加载页面?

更新代码

HTML:

<form [formGroup]="submitForm" novalidate [id]="submitFormId" method="post" isolate-form>
    <input type="text"/>
    <input type="hidden" name="Reference" [value]="data.reference">
    <input type="hidden" name="Action" [value]="data.action">
    <button class="btn" (click)="save()">Save</button>
</form>

TS:

public save() {
        let $form = $('#submitFormId');
        $form.attr('action', this.data.crnUrl);
        $form.submit();
    }

【问题讨论】:

  • 你能显示 HTML 表单吗?和提交方法?
  • 通过更新的查询参数使用路由器导航。这不会重新加载页面。
  • @TwoHorses,我更新了可能对 html 和 ts 代码提出的问题
  • @Faisal,我调用后端,后端会做重定向url,我无法导航路由器
  • 因为使用原生表单提交,浏览器会重新加载页面。您需要使用(ngSubmit) 自己处理表单提交(并删除method="post" 属性)

标签: angular angular-routing angular-router


【解决方案1】:

因为你使用的是原生表单提交,浏览器会重新加载页面。您需要在 Angular 内处理表单提交以防止这种行为。

  <form [formGroup]="submitForm" novalidate [id]="submitFormId" isolate-form (ngSubmit)="save()">
    <input type="text"/>
    <input type="hidden" name="Reference" [value]="data.reference">
    <input type="hidden" name="Action" [value]="data.action">
    <button class="btn" type="submit">Save</button>
</form>

然后在您的组件中使用HttpClient自己发送请求

  constructor(private http: HttpClient) {}

  public save() {
        let body = {}
        // Get form fields here using FormGroup, and put them into body
        this.http.post(this.data.crnUrl, body)
    }

另外,不要将 JQuery 与 angular 一起使用,因为 $form.submit() 会导致您的页面重新加载。

【讨论】:

  • 这是错误的答案。你能解释一下吗?
  • 是的,我在 appModule 和 childModule 中添加了
  • 我添加了一个解释,这个解决方案解决了我的确切问题。如果没有帮助,您可以编辑您的问题并添加 HTML 表单和提交方法吗?
猜你喜欢
  • 1970-01-01
  • 2015-06-17
  • 2017-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-04
  • 2019-10-21
  • 2017-06-26
相关资源
最近更新 更多