首页 > 解决方案 > post请求json中的角度getter和setter行为差异

问题描述

这是一个 Angular 9 + ASP.NET Core 3.1 应用程序。这是我使用的模型,我的问题依赖于此。

export class HeadingModel {
id: number;

private colourVal: string;
public get colour() {
    //code
}
public set colour(value) {
    //code
}
.
.
.etc

}

在左侧,您会看到在后端创建实体的发布请求的 JSON 请求正文。在右侧,您会看到用于更新后端实体的 put 请求的 JSON 请求正文。(所以我发送了一个获取请求,对收到的模型进行一些更改并将其发回)

我的问题是但是在创建请求时,角度使用我的私有 var 名称而不是使用 getter 的名称。(颜色值)

但是在发布请求中,它使用了 getter 的名称,这是正确的。

为什么会有不同的行为?我如何解决它?

在此处输入图像描述

有我的组件代码

createHeading(): void {
this.requestManagerService.create
  (this.headingWrapperModel, '/iot/Headings/Add').subscribe(
    (res) => {
      if (res) {
        this.toastrService.success('Heading created successfully', '', {
          disableTimeOut: false,
        });
        this.resetForm();
        this.showSpinner = false;
      } else {
        this.toastrService.error('An error occurred while creating the heading.', '', {
          disableTimeOut: false,
        });
      }
    },
    (error) => {
      console.error();
      this.showSpinner = false;
      this.toastrService.error(
        'An error occurred while creating the heading. Please contact administrator.',
        '',
        { disableTimeOut: false }
      );
    }
  );

}

updateHeading(): void {
    this.requestManagerService.update
      (this.headingWrapperModel, '/iot/Headings/Update').subscribe(
        (res) => {
          if (res) {
            this.toastrService.success('Heading updated successfully', '', {
              disableTimeOut: false,
            });
            this.resetForm();
            this.showSpinner = false;
          } else {
            this.toastrService.error('An error occurred while updating the heading.', '', {
              disableTimeOut: false,
            });
          }
        },
        (error) => {
          console.error();
          this.showSpinner = false;
          this.toastrService.error(
            'An error occurred while updating the heading. Please contact administrator.',
            '',
            { disableTimeOut: false }
          );
        }
      );
  }

这是我的服务代码

public create<T>(item: T, endpoint: string): Observable<T> {
return this.httpClient.post<T>(environment.boardpacAPIURL + endpoint, item).pipe(
  catchError(this.handleError<T>('RestApiHttpService')));

}

public update<T>(item: T, endpoint: string): Observable<T> {
return this.httpClient.put<T>(environment.boardpacAPIURL + endpoint, item).pipe(
  catchError(this.handleError<T>('RestApiHttpService')));

}

标签: angulartypescriptangular9

解决方案


我认为您没有发送相同的对象。在更新的情况下,您可能会用查询的结果覆盖您的对象,因此该对象没有getter 或setter,是get 请求的结果。

当您更改值时,您不会直接更改属性。

在帖子的情况下,您仍然拥有具有 getter 和 setter 的对象,并且当您分配一个值时,您正在提供 _varible。


推荐阅读