Object http请求中的Angular JSON对象

时间:2017-09-02 14:59:23

标签: angular angular-template

我正在尝试访问Json对象我正在获取数据。但它显示错误。如何在没有任何错误的情况下获取数据

ERROR TypeError: Cannot read property 'DATA' of undefined
    at Object.View_DosminusComponent_0._co [as updateDirectives] (DosminusComponent.html:3)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13075)
    at checkAndUpdateView (core.es5.js:12255)
    at callViewAction (core.es5.js:12620)
    at execComponentViewsAction (core.es5.js:12552)
    at checkAndUpdateView (core.es5.js:12261)
    at callViewAction (core.es5.js:12620)
    at execComponentViewsAction (core.es5.js:12552)
    at checkAndUpdateView (core.es5.js:12261)
    at callWithDebugContext (core.es5.js:13475)


// Component

import { DosminusService } from './../services/dosminus.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-dosminus',
  templateUrl: './dosminus.component.html',
  styleUrls: ['./dosminus.component.css']
})
export class DosminusComponent implements OnInit {

  dosMinusData: any;
  constructor(private dosminusService: DosminusService) { 

  }

  ngOnInit() {
    this.dosminusService.getDosMinusRecords()
    .subscribe(response => {
      this.dosMinusData = response.json();
    })
  }

}





//Service 
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class DosminusService {

  constructor(private http: Http) {

   }

   getDosMinusRecords(){
     return this.http.get('assets/Jsondata/dosminus.json');
   }

}

//JSON

{
    "DATA":{
        "kpiValue":"10",
        "kpiColor":"#A21313"
    }
}

<div class="e2e-dosminus">
  <div class="dosminus-center">
    <div class="dosminus-number-circle" [ngStyle]="{'backgroundColor': dosMinusData.DATA.kpiColor}">
    {{ dosMinusData.DATA.kpiValue }}
   </div>
  </div>
  <h4> Dos(-) </h4>
</div>

2 个答案:

答案 0 :(得分:1)

使用安全导航操作员 ? ,以避免在数据不存在时出错

<div class="dosminus-number-circle" [ngStyle]="{'backgroundColor': dosMinusData.DATA.kpiColor}">
    {{ dosMinusData?.DATA?.kpiValue }}
</div>

答案 1 :(得分:1)

如果你问我,我认为Observable +异步管道方法比elvis操作员(?)更清晰:

export class DosminusComponent implements OnInit {

  dosMinusData$: Observable<any>;
  constructor(private dosminusService: DosminusService) { 

  }

  ngOnInit() {
    this.dosMinusData$ = this.dosminusService.getDosMinusRecords();
  }
}

<ng-container *ngIf="dosMinusData$ | async as dosMinusData">
  <div class="dosminus-number-circle" [ngStyle]="{'backgroundColor': 
    dosMinusData.DATA.kpiColor}">
    {{ dosMinusData.DATA.kpiValue }}
  </div>
</ng-container>

@Injectable()
export class DosminusService {

  constructor(private http: Http) {

   }

   getDosMinusRecords(){
     return this.http.get('assets/Jsondata/dosminus.json').map(r => r.json());
   }

}