Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

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

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

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...