Angular中无法将类型'Promise <any>'分配给类型'any []'错误

时间:2018-11-29 13:38:13

标签: angular

我有此代码:

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

@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 = [];
  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_name: person.p_name,
      p_cost: person.p_cost
    };
    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.json();
        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;
          }
        }
      });
  }
}

...并且运行ng serve时收到此错误:

ERROR in src/app/update-person/update-person.component.ts(49,9): error TS2322: Type 'Promise<any>' is not assignable to type 'any[]'.
  Property 'length' is missing in type 'Promise<any>'.

错误在this.person = res.json();

处出现

2 个答案:

答案 0 :(得分:1)

无需使用json()

尝试这样的代码-

this.person = res;

在您使用httpClient进行请求时,默认情况下,订阅时它将以json格式给您答复,因此您可以忽略它。

答案 1 :(得分:0)

这对我有用:

person: any;