更新 div 以显示用户 Angular 执行的表单提交时出现问题

Problem with updating the div to display the form submission performed by the user Angular

我想在提交表单后显示用户执行的提交,方法是隐藏表单区域并在该区域显示响应。

所以在提交表单时,我应该显示一个垫子旋转器,直到从服务器收到响应。

component.html文件的代码如下:

  <div fxFlex [hidden]="!submitted">
    <mat-list *ngIf="feedback">
      <mat-list-item>
        <h4>Your Submission</h4>
        <p matLine>Id: {{feedback.id}}</p>
        <p matLine>First Name: {{feedback.firstname}}</p>
        <p matLine>Last Name: {{feedback.lastname}}</p>
        <p matLine>Tel. Number: {{feedback.telnum}}</p>
      </mat-list-item>

    </mat-list>

    <div [hidden]="feedback">
      <mat-spinner></mat-spinner><h4>Submitting Form</h4>
    </div>
  </div>


和component.ts部分如下:

   this.feedbackService.submitFeedback(this.feedback)
    .subscribe(
      feedback => (this.feedback = feedback,
      console.log(feedback))

    );

这是服务文件

submitFeedback(feedback: Feedback): Observable<Feedback> {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    };

    return this.http.post<Feedback>(baseURL + 'feedback/', feedback, httpOptions)
    .pipe(catchError(this.processHTTPMsgService.handleError));
  }

所以问题是,当我提交表单时,我正在向服务器发送 POST 请求以发送反馈。现在我想显示用户提交的反馈,但是在点击提交时,它直接显示了我在表单中使用的值,而不是使用服务器的值,但是在 2 秒后(我设置了延迟服务器响应为 2 秒)同一区域使用从服务器接收到的值进行更新,这是我实际希望它工作的方式。

现在我想避免使用即时表单值并希望等待 2 秒以便微调器也可见。

我想我把问题解释清楚了。

您可以简单地声明一个标志来隐藏或不隐藏这块表单。

<div fxFlex [hidden]="!submitted">

    <mat-list *ngIf="!waiting && feedback else loading">
        <mat-list-item>
        <h4>Your Submission</h4>
        <p matLine>Id: {{feedback.id}}</p>
        <p matLine>First Name: {{feedback.firstname}}</p>
        <p matLine>Last Name: {{feedback.lastname}}</p>
        <p matLine>Tel. Number: {{feedback.telnum}}</p>
        </mat-list-item>

    </mat-list>

    <ng-template #loading>
        <div>
            <mat-spinner></mat-spinner><h4>Submitting Form</h4>
        </div>
    </ng-template>

</div>

ng-template 定义了默认情况下不会呈现的模板。 loading(模板)的渲染将由 *ngIf.

触发

*ngIf 计算第二个标志。
waiting 应在发送 HTTP 请求 时设置为 true,并在响应到达时设置为 false

this.waiting = true;
this.feedbackService.submitFeedback(this.feedback)
    .subscribe(
      feedback => {
            this.feedback = feedback;
            console.log(feedback);
            this.waiting = false;
      }, err => this.waiting = false; // In case the HTTP request fails
);

试试吧。