在用角度5/6编辑后如何保存更改?

时间:2018-12-27 00:54:10

标签: javascript angular typescript

我正在建立一个帐户信息页面。我想允许编辑并保存更改(即:名称),但是我又得到了相同的旧名称。我的代码如下

<div >
    <mat-form-field class="simple-form-field-50" *ngIf="isEditEnable">
      <input matInput placeholder="Name" [(ngModel)]="name">
    </mat-form-field>
    <span *ngIf="!isEditEnable">Name : {{user?.givenName}} </span>
    <button style="border:0;" *ngIf="!isEditEnable" (click)="onEdit()"><span><mat-icon style="font-size:16px;" matSuffix>create</mat-icon></span></button>
    <button *ngIf="isEditEnable" mat-raised-button color="primary" (click)="onEdit()">Submit</button>
</div>

TS代码:

export class ProfileComponent implements OnInit {
  user: User;

  constructor(
    private http: HttpClient,
    ) { }

  isEditEnable = false;

  ngOnInit() {
    this.http.get<User>('/api/user/details', {})
        .subscribe((user) =>  {
          this.user = user;
        });
  }
  onEdit() {
  this.isEditEnable = !this.isEditEnable;
  }
}

代码输出:

[1](https://imgur.com/nxiExeH.png

点击“编辑”按钮后:

[2](https://imgur.com/599SIF4.png

点击提交后,它会返回旧名称而不会更改

[3](https://imgur.com/nxiExeH.png

1 个答案:

答案 0 :(得分:0)

好吧,看来您永远不会更新用户的name属性,并且记得要更新数据库中的用户(为此,您需要添加一个端点)

<div >
    <mat-form-field class="simple-form-field-50" *ngIf="isEditEnable">
        <input matInput placeholder="Name" [(ngModel)]="name">
    </mat-form-field>
    <span *ngIf="!isEditEnable">Name : {{user?.givenName}} </span>
    <button style="border:0;" *ngIf="!isEditEnable" (click)="onEdit()">
        <span><mat-icon style="font-size:16px;" matSuffix>create</mat-icon></span>
    </button>
    <button *ngIf="isEditEnable" mat-raised-button color="primary" (click)="onEdit()">
        Submit
    </button>
</div>

export class ProfileComponent implements OnInit {
    user: User;
    name: string;

    constructor(
      private http: HttpClient,
    ) { }

    isEditEnable = false;

    ngOnInit() {
      this.http.get<User>('/api/user/details', {})
          .subscribe((user) =>  {
            this.user = user;
          });
    }

    // assume you have or will add an endpoint to handle user update
    updateUser(user) {
        this.http.put((`/api/user/${this.user.id}`, this.user))
    }

    onEdit() {
        if (this.isEditEnable && this.user.givenName !== this.name) {                
                // assign new name to the user
                this.user.givenName = this.name;
                // use api update the user in your database
                this.updateUser()
        }
        this.isEditEnable = !this.isEditEnable
    }
}

以下内容转到后端部分(假设您可能将节点与express一起使用?) 您的路由器可能有一个名为users.js的文件,那里有一个定义为以下内容的get端点

this.router.get('details', someFunctionThatGetsUser);

您将需要再添加一个

this.router.put('/:id', functionToUpdateUserInDB);

并在用户服务中添加一个功能,以在数据库中更新该功能