我将如何在地图函数中指定数据类型?
How would I specify data types in the map function?
我从服务器获取数据,这是一个包含四个不同对象类型数组的对象。现在,我尝试在订阅可观察对象之前映射数据,以便我可以在前端使用正确的 类:
getData(){
return this.http.get(this.authUrl + 'get/auf-data').pipe(
map(({material, mat_auf, lokals, auf_analysen}) => {
material.map(material => this.materialAdapter.adapt(material));
mat_auf.map(auf => this.materialAufAdapter.adapt(auf));
lokals.map(lokal => this.lokalAdapter.adapt(lokal));
auf_analysen.map(analyse => this.aufAnalyseAdapter.adapt(analyse));
})
);
}
响应是包含四个不同数组的对象类型,但不知何故我收到错误:
Property 'material' does not exist on type 'Object' (repeated for: mat_auf, lokals and auf_analysen)
如何在 map 函数中指定数据类型?
响应时间的定义方式如下
getData() {
return this.http.get<{ material: any, mat_auf: any, lokals: any, auf_analysen: any; }>('get/auf-data').pipe(
map(({ material, mat_auf, lokals, auf_analysen }) => {
material.map(material => this.materialAdapter.adapt(material));
mat_auf.map(auf => this.materialAufAdapter.adapt(auf));
lokals.map(lokalisation => this.lokalAdapter.adapt(lokal));
auf_analysen.map(analyse => this.aufAnalyseAdapter.adapt(analyse));
})
);
}
如果查看 httpClient
的类型定义,您会发现 get 方法的定义之一是
get<T>(url: string, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe: 'events';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpEvent<T>>;
当然,不用 any
在定义响应正文时使用您需要的任何内容。
我从服务器获取数据,这是一个包含四个不同对象类型数组的对象。现在,我尝试在订阅可观察对象之前映射数据,以便我可以在前端使用正确的 类:
getData(){
return this.http.get(this.authUrl + 'get/auf-data').pipe(
map(({material, mat_auf, lokals, auf_analysen}) => {
material.map(material => this.materialAdapter.adapt(material));
mat_auf.map(auf => this.materialAufAdapter.adapt(auf));
lokals.map(lokal => this.lokalAdapter.adapt(lokal));
auf_analysen.map(analyse => this.aufAnalyseAdapter.adapt(analyse));
})
);
}
响应是包含四个不同数组的对象类型,但不知何故我收到错误:
Property 'material' does not exist on type 'Object' (repeated for: mat_auf, lokals and auf_analysen)
如何在 map 函数中指定数据类型?
响应时间的定义方式如下
getData() {
return this.http.get<{ material: any, mat_auf: any, lokals: any, auf_analysen: any; }>('get/auf-data').pipe(
map(({ material, mat_auf, lokals, auf_analysen }) => {
material.map(material => this.materialAdapter.adapt(material));
mat_auf.map(auf => this.materialAufAdapter.adapt(auf));
lokals.map(lokalisation => this.lokalAdapter.adapt(lokal));
auf_analysen.map(analyse => this.aufAnalyseAdapter.adapt(analyse));
})
);
}
如果查看 httpClient
的类型定义,您会发现 get 方法的定义之一是
get<T>(url: string, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe: 'events';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpEvent<T>>;
当然,不用 any
在定义响应正文时使用您需要的任何内容。