"Type 'Object' is not assignable to type" with new HttpClient / HttpGetModule

midnightnoir picture midnightnoir · Aug 1, 2017 · Viewed 34.3k times · Source

Following Google's official Angular 4.3.2 doc here, I was able to do a simple get request from a local json file. I wanted to practice hitting a real endpoint from JSON placeholder site, but I'm having trouble figuring out what to put in the .subscribe() operator. I made an IUser interface to capture the fields of the payload, but the line with .subscribe(data => {this.users = data}) throws the error Type 'Object' is not assignable to type 'IUser[]'. What's the proper way to handle this? Seems pretty basic but I'm a noob.

My code is below:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IUsers } from './users';

@Component({
  selector: 'pm-http',
  templateUrl: './http.component.html',
  styleUrls: ['./http.component.css']
})
export class HttpComponent implements OnInit {
  productUrl = 'https://jsonplaceholder.typicode.com/users';
  users: IUsers[];
  constructor(private _http: HttpClient) { }

  ngOnInit(): void {    
    this._http.get(this.productUrl).subscribe(data => {this.users = data});
  }

}

Answer

Mark Pieszak - Trilon.io picture Mark Pieszak - Trilon.io · Aug 1, 2017

You actually have a few options here, but use generics to cast it to the type you're expecting.

   // Notice the Generic of IUsers[] casting the Type for resulting "data"
   this.http.get<IUsers[]>(this.productUrl).subscribe(data => ...

   // or in the subscribe
   .subscribe((data: IUsers[]) => ...

Also I'd recommend using async pipes in your template that auto subscribe / unsubscribe, especially if you don't need any fancy logic, and you're just mapping the value.

users: Observable<IUsers[]>; // different type now

this.users = this.http.get<IUsers[]>(this.productUrl);

// template:
*ngFor="let user of users | async"