更新Angular中的CRUD组件不保存数据

时间:2018-11-29 17:40:02

标签: angular typescript json-server

这是我的更新组件:

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变量进行的其他操作,以及相应的错误。

1 个答案:

答案 0 :(得分:1)

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

我通常使用post创建新数据并放置以更新现有数据。

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

  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关键字而不是箭头函数=>构建函数时,this的作用域为该函数,并且您实际上并没有访问类级别的{ {1}}

4)我不确定是否同时需要personObjperson

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

您可以在这里以堆栈闪电的方式查看/执行它:https://stackblitz.com/edit/deborahk-crud

相关问题