【问题标题】:Display a Hashmap json from REST API, as a table in Angular 5显示来自 REST API 的 Hashmap json,作为 Angular 5 中的表格
【发布时间】:2018-04-03 08:38:07
【问题描述】:

我有一个 REST API 返回一个 Hashmap <String,<String,Integer>>。我需要使用这个 Hashmap Json 在 Angular 5 中显示一个表格。到目前为止,我已经尝试了以下方法,但表格仍然是空的。我不太确定如何在 HTML 文件中正确访问模型类中的嵌套对象。我哪里错了?

这是我定义了 HashMap 结构的 frequency-table.model.ts 文件。

export interface FrequencyTable {
obj: {
    key: String;
    val: {
        key_in: String;
        val_in: Number;
    };
} 
}

这是 HTML 文件

<div class="container">
<div class="row">
    <table class="table">
        <thead class="thead-inverse">
        <tr>
            <th class="text-center">Thread Name</th>
            <th class="text-center">Query</th>
            <th class="text-center">Frequency</th>

        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let post of _postsArray">
            <td class="text-center" style="width: 15px;">{{post.key}}</td>
            <td class="text-center" style="width: 15px;">{{post.val.key_in}}</td>
            <td class="text-center" style="width: 200px;">{{post.val.val_in}}</td>

        </tr>
        </tbody>
    </table>
</div>

这是 frequency-table.component.ts 文件

export class FrequencyTableComponent implements OnInit {
  _postsArray: FrequencyTable[];

 constructor(private tableService: TableService) { }
 getPosts(): any {
  this.tableService.getPosts()
    .subscribe(
        resultArray => this._postsArray = resultArray,
        error => console.log("Error :: " + error)
    )
 }

  ngOnInit() {

  }

这是 service.ts 文件

@Injectable()
export class TableService {

constructor(private http: HttpClient) {}
getPosts(): Observable<FrequencyTable[]> {
return this.http
    .get('\getQueryCount')
    .map((response: Response) => {
        return <FrequencyTable[]>response.json();
    })
    .catch(this.handleError);
   }

    private handleError(error: Response) {
    return Observable.throw(error.statusText);
  }
  }

这是返回 Hashmap json 的 REST API:

@RestController
public class QueryCounterController{

@Autowired
ReadFileService rfservice;


@GetMapping("/getQueryCount")
@ResponseBody
public Map<String, Object>  getQueryCount() throws IOException{

String filename = "file.txt";

return (rfservice.readFile(filename));}

}

Json 示例:

 {
     "key1": {
     "xyz": 3,
     "abc": 2
     },
     "key-2": {
     "pqr": 3,
     "uvw": 2
     }
  }

【问题讨论】:

  • var obj = this.getPosts(); 中可能出错的一件事——这行代码立即返回,无需等待 http 请求完成。您应该将您的逻辑移动到 subscribe 函数中。
  • 我删除了 ngOnInit() 的代码。还是不行
  • @apoorva96,您在 Angular 应用中的响应转换无效。您没有发送对象列表作为响应。您发送的地图仅表示一个对象。因此,在 service.ts 中将您的响应转换为您喜欢的对象列表
  • @swarooppallapothu 你能用一些代码解释一下吗
  • @apoorva96,您可以通过 2 种方式进行操作。 #1。将 java 中的返回类型更改为 List 而不是 Map。 #2。将您在 service.ts 中的响应转换为诸如 FrequencyTable 之类的对象列表

标签: java json angular


【解决方案1】:

我通过以下更改解决了这个问题:

frequency-table.component.ts

export class FrequencyTableComponent implements OnInit {
_postsArray: Array<any> = [];
 constructor(private tableService: TableService) { }

 ngOnInit() {

  this.tableService.getPosts().subscribe((data: any) => {
  console.log(data);
   Object.keys(data).forEach(key => {
    var obj1 = data[key];
    console.log('key is ' + key);
     Object.keys(obj1).forEach(key1 => {
      console.log('key inner is ' + key1 + ' val is ' + obj1[key1]);
      this._postsArray.push({k: key, l: key1, m: obj1[key1]});
    })
  });
  console.log('array is ' + this._postsArray.toString());

   });
  }

frequency-table.service.ts

@Injectable()
export class TableService {

constructor(private http: HttpClient) {}
getPosts(): any {
return this.http.get('/getQueryCount');
}

frequency-table.component.html

<div class="container">
<div class="row">
    <table class="table">
        <thead class="thead-inverse">
        <tr>
            <th class="text-center">Thread Name</th>
            <th class="text-center">Query</th>
            <th class="text-center">Frequency</th>

        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let post of _postsArray">
            <td class="text-center" style="width: 15px;">{{post.k}}</td>
            <td class="text-center" style="width: 15px;">{{post.l}}</td>
            <td class="text-center" style="width: 200px;">{{post.m}}</td>

        </tr>
        </tbody>
    </table>
</div>

我暂时删除了 frequency-service.model.ts 类。现在我得到了想要的桌子。感谢@SEY_91 的帮助。

【讨论】:

    【解决方案2】:

    getPosts 正在返回地图的 Observable:

      ngOnInit(){
        this.getPosts().subscribe(obj => {
          Object.keys(obj).forEach(key => {
            this._postsArray.push({obj: {key: key, val : { key_in:obj[key].key, val_in :obj[key].val}}});
          });
        });
      }
    

    HTML:

    <tr *ngFor="let post of _postsArray">
                <td class="text-center" style="width: 15px;">{{post.obj.key}}</td>
                <td class="text-center" style="width: 15px;">{{post.obj.val.key_in}}</td>
                <td class="text-center" style="width: 200px;">{{post.obj.val.val_in}}</td>
    
            </tr>
    

    【讨论】:

    • 最后一行不应该是obj.key吗?
    • 你的意思是 {obj: {key: key, val : obj[key] } } ??
    • 添加json响应的结构也许我能找出问题
    • 我现在应该如何在 HTML 中访问它?
    • 在编辑问题之前,我尝试以与您在 ngOnInit 中相同的方式解析响应,否则我不知道 json 响应结构如何
    猜你喜欢
    • 1970-01-01
    • 2016-06-16
    • 2017-10-11
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多