以angular2

时间:2017-09-05 19:45:20

标签: json angular

我正在使用angular2从节点api获取数据。 Node api以类似

的格式返回数据
{"height":{"low":4,"high":0,"unsigned":true},"currentBlockHash":{"buffer":{"type":"Buffer","data":[8,4,18,32,197,125,99,165,77,70,46,19,215,237,19,57,219,242,168,130,134,153,184,56,68,211,255,62,122,245,216,154,192,254,179,139,26,32,169,218,156,201,73,252,127,198,103,103,43,100,81,90,113,109,163,137,159,156,140,148,125,28,104,79,145,218,72,145,206,6]},"offset":4,"markedOffset":-1,"limit":36,"littleEndian":true,"noAssert":false},"previousBlockHash":{"buffer":{"type":"Buffer","data":[8,4,18,32,197,125,99,165,77,70,46,19,215,237,19,57,219,242,168,130,134,153,184,56,68,211,255,62,122,245,216,154,192,254,179,139,26,32,169,218,156,201,73,252,127,198,103,103,43,100,81,90,113,109,163,137,159,156,140,148,125,28,104,79,145,218,72,145,206,6]},"offset":38,"markedOffset":-1,"limit":70,"littleEndian":true,"noAssert":false}} 

我只想在angular2前端显示low的值,但问题是我无法将json数据拆分为键值对。 angular2正在显示整个数据或什么都没有。 这是我的组件代码,它以json格式接收数据

import {Component,OnInit} from '@angular/core';
import { AppService } from '~/./../app/app.service';

@Component({
  selector: 'dashboard',
  styleUrls: ['./dashboard.scss'],
  templateUrl: './dashboard.html'
})
export class Dashboard implements OnInit {

  constructor(private AppService: AppService) {
  }

  ngOnInit(){
      this.getStats();
  }

  BlockchainHeight:any;

  getStats(){
      this.AppService.getblockchaininfo().subscribe(data=>{
          console.log(data);
          this.BlockchainHeight=data["_body"];
      });
  }


}

这是我显示数据的html代码

<div class="row">
  <div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col-4">
   <ba-card>
     <h3> Blockchain Height</h3>
     {{BlockchainHeight}}
   </ba-card>
  </div>

将json数据拆分成键值对的任何技巧或解决方案?

1 个答案:

答案 0 :(得分:0)

我不确定Angular2的具体细节,但这会将json字符串转换为只有普通的jilla

的对象
var jsonResponse = "{"height":{"low":4,"high":0,"unsigned":true},"currentBlockHash":{"buffer":{"type":"Buffer","data":[8,4,18,32,197,125,99,165,77,70,46,19,215,237,19,57,219,242,168,130,134,153,184,56,68,211,255,62,122,245,216,154,192,254,179,139,26,32,169,218,156,201,73,252,127,198,103,103,43,100,81,90,113,109,163,137,159,156,140,148,125,28,104,79,145,218,72,145,206,6]},"offset":4,"markedOffset":-1,"limit":36,"littleEndian":true,"noAssert":false},"previousBlockHash":{"buffer":{"type":"Buffer","data":[8,4,18,32,197,125,99,165,77,70,46,19,215,237,19,57,219,242,168,130,134,153,184,56,68,211,255,62,122,245,216,154,192,254,179,139,26,32,169,218,156,201,73,252,127,198,103,103,43,100,81,90,113,109,163,137,159,156,140,148,125,28,104,79,145,218,72,145,206,6]},"offset":38,"markedOffset":-1,"limit":70,"littleEndian":true,"noAssert":false}} "; 
var decodedJsonObject = JSON.parse(jsonResponse);
var low = decodedJsonObject.height.low;