英文:
Return a HashMap from HTTP GET using angular 10
问题
以下是翻译好的内容:
我正在使用以下版本。
Angular CLI:10.0.1
Node:12.18.2
操作系统:win32 x64
Angular:10.0.2
我有一个Java Spring Boot服务(运行良好),它将数据作为HashMap返回。
Map<String,List<String>>;
以下是服务调用的输出:
// 20200728103825
// http://localhost:1234/config-data
{
"books": [
"ABC",
"PQR",
"XYZ",
"QWT",
"LMN",
],
"categories": [
"FICTION",
"DRAMA"
]
}
我还有一个简单的调用,它返回书籍列表(作为字符串)。例如:
// 20200728112259
// http://localhost:1234/book-data
[
"ABC",
"PQR",
"XYZ",
"QWT",
"LMN",
]
现在,我想在我的Angular代码中使用这些数据。
我已经定义了以下服务。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(
private http: HttpClient
) { }
loadBookData(){
console.log("loadBookData 服务");
return this.http.get<string[]>('http://localhost:1234/book-data');
}
loadConfigData() {
console.log("loadConfigData 服务");
// 在这里寻找帮助
}
}
基本上,我可以读取book-data(string[])。
然而,我应该如何读取来自服务的HashMap等复杂数据?
英文:
I am using following version.
Angular CLI: 10.0.1
Node: 12.18.2
OS: win32 x64
Angular: 10.0.2
I have a Java spring boot service (working well) which returns the data as a HashMap.
Map<String, List<String>>
Following is the output of the service call:
// 20200728103825
// http://localhost:1234/config-data
{
"books": [
"ABC",
"PQR",
"XYZ",
"QWT",
"LMN",
],
"categories": [
"FICTION",
"DRAMA"
]
}
I also have a simple call which returns list of books (as String). E.g.
// 20200728112259
// http://localhost:1234/book-data
[
"ABC",
"PQR",
"XYZ",
"QWT",
"LMN",
]
Now, I want to use this in my Angular code.
I have the service defined as follows.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(
private http: HttpClient
) { }
loadBookData(){
console.log("loadBookData Service");
return this.http.get<string[]>('http://localhost:1234/book-data');
}
loadConfigData() {
console.log("loadConfigData Service");
// Looking for help here
}
}
Basically I am able to read the book-data (string[]).
However, how should read complex data which is HashMap from service?
答案1
得分: 0
你可以像这样声明一个模型:
export class Result {
books: string[];
categories: string[];
}
你的 loadConfigData
应该如下所示:
loadConfigData() {
console.log("loadConfigData Service");
return this.http.get<Result>('http://localhost:1234/config-data')
.pipe(
map((data: Result) => {
console.log(data.books);
console.log(data.categories);
})
);
}
英文:
you can declare a model like this:
export class Result{
books: string[];
categories: string[];
}
your loadConfigData should be as follows:
loadConfigData() {
console.log("loadConfigData Service");
return this.http.get<Result>('http://localhost:1234/config-data')
.pipe(
map((data:Result) => {
console.log(data.books);
console.log(data.categories);
})
);
}
</details>
专注分享java语言的经验与见解,让所有开发者获益!
评论