如何从Angular 2

时间:2017-03-29 11:34:50

标签: json angular

我是Angular 2中的新手,我很失落。我有一个响应/ rest / alertsDashboard的JSON Web服务。它返回类似于:

{
  "total": {
    "totalOperations": 2573,
    "totalOperationsAlert": 254,
    "totalOperationsRisk": 34
  },
  "alerts": [
      {
        codAlert: "L1",
        description: "Alert 1",
        value: 1
      },
      {
        codAlert: "L2",
        description: "Alert 2",
        value: 2
      },
      ...
  ]
}

所以我定义了一个DashboardComponent组件和一个AlertDashboardService服务。例如,我希望显示totalOperations和totalOperationsAlert。我不知道我是否以正确的方式做到了。

在dashboard.component.ts中我有:

...
@Component({
  selector: 'app-dashboard',
  template: `
    <p>{{totalAlertsDashboard.totalOperations}}</p>
    <p>{{totalAlertsDashboard.totalOperationsAlert}}</p>
    ...
  `
})
export class DashboardComponent implements OnInit {
  totalAlertsDashboard: TotalAlertsDashboard;
  alertsDashboard: AlertDashboard[];

  constructor(private alertsDashboardService: AlertsDashboardService) { }

  ngOnInit() {
    this.alertsDashboardService.get().then(
      response => {
        this.totalAlertsDashboard = response.totalAlertsDashboard;
        this.alertsDashboard = response.alertsDashboard;
      }
    );
  }
}

在alerts-dashboard.service.ts中,我有:

...
export class AlertsDashboard {
    totalAlertsDashboard: TotalAlertsDashboard;
    alertsDashboard: AlertDashboard[];
}

export class TotalAlertsDashboard {
    totalOperations: number;
    totalOperationsAlert: number;
    totalOperationsRisk: number;
}

export class AlertDashboard {
    codAlert: string;
    description: string;
    value: number;
}

@Injectable()
export class AlertsDashboardService {
    private headers = new Headers({ 'Content-Type': 'application/json' });
    private url = environment.urlAPI + '/rest/alertsDashboard';

    constructor(private http: Http) { }

    get(): Promise<AlertsDashboard> {
        var vm = this;

        let params = new URLSearchParams();

        return vm.http.get(vm.url, { search: params })
        .toPromise()
        .then(response => {
            var responseJson: AlertsDashboard = response.json() ;
            console.log(responseJson); // it prints the JSON correctly
            return responseJson;
        });
  }
}

我希望你能帮助我。

1 个答案:

答案 0 :(得分:2)

试试这个:

ngOnInit() {
    this.alertsDashboardService.get().then(
      response => {
        this.totalAlertsDashboard = response.total;
        this.alertsDashboard = response.alerts;
      }
    );
  }

在alerts-dashboard.service.ts

export class AlertsDashboard {
    total: TotalAlertsDashboard;
    alerts: AlertDashboard[];
}

模板:

<p>{{totalAlertsDashboard?.totalOperations}}</p>