Angular 获取对象的数组
嗨,我正在尝试从angular中的get请求获取数据。我有一套像这样的公寓:Angular 获取对象的数组,angular,http,get,Angular,Http,Get,嗨,我正在尝试从angular中的get请求获取数据。我有一套像这样的公寓: export class Apartment { id: number; address: string; constructor(id: number, name: string) { this.id = id; this.name = name; } } { "id" : 0, "address: "not assinged yet" } 服务 @
export class Apartment {
id: number;
address: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
{
"id" : 0,
"address: "not assinged yet"
}
服务
@Injectable({
providedIn: 'root'
})
export class Service {
baseURL = 'http://localhost:3000';
constructor(private httpClient: httpClient) {}
getApartments() {
return this.httpClient.get(this.baseURL + '/apartments');
}
}
组件
export class SettingsComponent implements OnInit {
apartments: Apartment[] = [];
constructor(private apiService: Service) {
// todo: fetch data here...
}}
我有一个可以工作的rest api和一个可以读取的json文件,如下所示:
export class Apartment {
id: number;
address: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
{
"id" : 0,
"address: "not assinged yet"
}
如何读取数据并将其强制转换为公寓阵列?在订阅中,您只需像这样声明
(数据:any)
constructor(private apiService: Service) {
this.apiService.getApartments().subscribe((data:any)=>{
this.apartments = data;
});
}
您的API是否返回公寓列表?如果是,你可以这样做-
export class SettingsComponent implements OnInit {
apartments: Apartment[] = [];
constructor(private apiService: Service) {}
}
ngOnInit(){
this.fetchApartments();
}
fetchApartments(){
this.apiService.getApartments().subscribe(
response => {
this.apartments = response;
}
);
}
或者
如果您没有任何特定于类的方法,我自己也不会在这里使用类,只是一个接口。但是,如果您确实希望拥有一个类并将数据实例创建到该类,则需要映射数据,这里假设您得到一个数组。同时告诉angular您在请求中得到了什么:
get公寓(){
返回此.httpClient.get(this.baseURL+'/repartments').pipe(
地图((arr)=>arr.map(x=>新公寓(x.id,x.address)))
)
}
然后在组件中:
ngOnInit(){
this.apiService.get公寓()
.subscribe((数据:公寓[])=>this.partments=data);
}
但正如我提到的,如果类中没有方法,我会使用接口:
导出接口单元{
id:编号;
地址:字符串;
}
还有get请求,简单地说:
get公寓(){
返回this.httpClient.get(this.baseURL+'/repartments')
}
并订阅上述组件。不要使用任何组件。这违背了打字脚本的目的。始终键入数据,即使只是为了您自己。假设您希望通过调试使您的生活更轻松;)在这种情况下,他为单元定义了类型,如果你不使用任何,它会显示错误cant not castWell,然后使用定义的类型,而不是
any
。如果我使用一个接口和相对的getApartments方法,我仍然需要订阅或getApartments调用就足够了?对于http请求,我们处理的是冷可观察的,您总是需要订阅,或者使用subscribe
或者在模板中使用async
管道:)如果不需要处理TS文件中接收的数据,使用async管道非常方便:但是如果您需要以某种方式操作TS文件中的数据,我建议使用subscribe
。