0

这是我的更新组件:

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 变量尝试过的其他一些事情以及我得到的相应错误。

4

1 回答 1

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功能?(它在哪里被调用?)

function3) 当使用关键字而不是箭头函数来构建函数时=>,它的this作用域是函数,并且您实际上并没有访问类级别personObj

4)我不清楚两者的需要personpersonObj

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

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

于 2018-11-29T18:05:46.543 回答