“类型'对象'不可分配给类型".与新的HttpClient/HttpGetModule [英] "Type 'Object' is not assignable to type" with new HttpClient / HttpGetModule
问题描述
在此处是Google的官方Angular 4.3.2文档之后,我能够做一个简单的get
来自本地json文件的请求.我想练习从JSON占位符站点访问一个真实的端点,但是我在弄清楚要放在.subscribe()
运算符中的内容时遇到了麻烦.我创建了一个IUser
接口来捕获有效负载的字段,但是带有.subscribe(data => {this.users = data})
的行引发错误Type 'Object' is not assignable to type '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屋!