【问题标题】:Update CRUD component in Angular not saving data在 Angular 中更新 CRUD 组件不保存数据
【发布时间】:2019-05-01 20:27:50
【问题描述】:

这是我的更新组件:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-update-person',
  templateUrl: './update-person.component.html',
  styleUrls: ['./update-person.component.css']
})
export class UpdatePersonComponent implements OnInit {
  id: number;
  data: object = {};
  // person = []; //ERROR TypeError: Cannot read property 'length' of undefined
  // person = any; //ERROR Error: Uncaught (in promise): ReferenceError: any is not defined
  person: any; //ERROR TypeError: Cannot read property 'length' of undefined
  exist = false;
  personObj: object = {};
  private headers = new Headers({ 'Content-Type': 'application/json' });

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private http: HttpClient
  ) {}
  confirmationString: string = 'Person updated successfully !!';
  isUpdated: boolean = false;

  updatePerson = function(person) {
    this.personObj = {
      p_id: person.p_id,
      p_username: person.p_username,
      p_image: person.p_image
    };
    const url = `${'http://localhost:5555/person'}/${this.id}`;
    this.http
      .put(url, JSON.stringify(this.personObj), { headers: this.headers })
      .toPromise()
      .then(() => {
        this.router.navigate(['/']);
      });
  };
  ngOnInit() {
    this.route.params.subscribe(params => {
      this.id = +params['id'];
    });
    this.http
      .get('http://localhost:5555/person')
      .subscribe((res: Response) => {
        this.isUpdated = true;
        this.person = res;
        for (var i = 0; i < this.person.length; i++) {
          if (parseInt(this.person[i].id) === this.id) {
            this.exist = true;
            this.data = this.person[i];
            break;
          } else {
            this.exist = false;
          }
        }
      });
  }
}

这可以正常工作而不会引发任何错误。但是,单击更新按钮后,空白数据将保存到我的 json 服务器。

认为问题在于person: any;。您可以看到我使用该 person 变量尝试过的其他几件事以及我得到的相应错误。

【问题讨论】:

    标签: angular typescript json-server


    【解决方案1】:

    通常建议您将数据访问代码放入服务中,而不是组件中。

    我通常使用 post 来创建新数据并 put 更新现有数据。

    我的更新方法(在我的数据访问服务中)如下所示:

      updateProduct(product: Product): Observable<Product> {
        const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
        const url = `${this.productsUrl}/${product.id}`;
        return this.http.put<Product>(url, product, { headers: headers })
          .pipe(
            tap(() => console.log('updateProduct: ' + product.id)),
            // Return the product on an update
            map(() => product),
            catchError(this.handleError)
          );
      }
    

    请注意,我没有对传递的数据进行字符串化。我也没有将结果转换为承诺。

    关于您的代码:

    1) 考虑将数据访问代码移动到服务中。

    2) 你在哪里使用UpdatePerson 函数? (在哪里调用?)

    3) 使用 function 关键字而不是箭头函数 =&gt; 构建函数时,this 的作用域为函数,您实际上并未访问类级别 personObj

    4) 我不清楚是否需要 personpersonObj

    如果您想要一些具有创建、更新和删除操作的工作示例代码,您可以在此处找到示例:https://github.com/DeborahK/Angular-ReactiveForms/tree/master/APM

    您可以在此处的 stackblitz 中查看/执行它:https://stackblitz.com/edit/deborahk-crud

    【讨论】:

    • 哇!伟大的职位黛博拉!这是我在github.com/ps0305/angularCRUD 工作的仓库。基本上我所改变的只是从产品到人的模型。我将查看您共享的存储库,并研究您提出的建议。谢谢!!!
    • 快速浏览一下……我认为这更像是一个演示应用程序,而不是您为真实应用程序构建的示例。最佳实践是使用服务进行数据访问。来自 Angular 文档:angular.io/guide/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2018-06-20
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    相关资源
    最近更新 更多