Mark Locklear
Mark Locklear

Reputation: 5325

Type 'Promise<any>' is not assignable to type 'any[]' error in Angular

I have this code:

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;
          }
        }
      });
  }
}

...and am getting this error when I run 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>'.

The error is down at this.person = res.json();

Upvotes: 1

Views: 4595

Answers (2)

Michael Aigboeghian
Michael Aigboeghian

Reputation: 11

This worked for me:

person: any;

Upvotes: 1

Pardeep Jain
Pardeep Jain

Reputation: 86740

No need to use json().

Try your code like this -

this.person = res;

As you are using httpClient for your request, on subscribe it will give you response in json format by default, so you can omit this.

Upvotes: 1

Related Questions