“类型‘对象’不可分配给类型"使用新的 HttpClient/HttpGetModule [英] "Type 'Object' is not assignable to type" with new HttpClient / HttpGetModule
问题描述
遵循 Google 的官方 Angular 4.3.2 文档在这里,我能够做一个简单的 从本地 json 文件获取
请求.我想练习从 JSON 占位符站点点击真正的端点,但我无法弄清楚要在 .subscribe()
运算符中放入什么.我制作了一个 IUser
接口来捕获有效负载的字段,但是带有 .subscribe(data => {this.users = data})
的行抛出错误 <代码>类型对象"不可分配给类型IUser[]".处理这个问题的正确方法是什么?看起来很基本,但我是个菜鸟.
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.
我的代码如下:
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});
}
}
推荐答案
您实际上在这里有一些选择,但使用泛型将其转换为您期望的类型.
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"
这篇关于“类型‘对象’不可分配给类型"使用新的 HttpClient/HttpGetModule的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!