将JSON视为角度应用中的列表

时间:2017-11-18 15:08:06

标签: angular model-view-controller core

如何在浏览器中显示单个JSON数据?

app.components.ts

ng build --production -host=myDomain.com

employee.service.ts

import { Component } from '@angular/core';
import { Http } from '@angular/http'
import { HttpClient } from '@angular/common/http';

import { EmployeeService } from './employee.service';
import { Employee } from './employee';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  employees: Employee[];

  constructor(private _httpService: Http, private employeeService: EmployeeService) { }

  ngOnInit() {
    this.getEmployees();
  }

  getEmployees(): void {

    this.employeeService.getEmployees().subscribe(data => {
      console.log(data);
    });

    this.employeeService.getEmployees()
      .subscribe(employees => this.employees = employees);
  }
}

app.component.html

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

import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';

import { Employee } from './employee';

@Injectable()
export class EmployeeService {

  constructor(public http: HttpClient, private _httpService: Http) { }

  employees: Employee[];

  getEmployees(): Observable<any> {

    console.log(this.http.get('/api/values'));

    return this.http.get('/api/values')
      .map(response => response);//.json());
    //.catch((error: any) => Observable.throw(
    //    { message: error.json().message, details: error.json().details }));
  }
}

employee.ts

<h1>Application says what?</h1>
<ul>
  {{employees}}
</ul>

现在我得到一个这样的结果:

  

[{“id”:“1”,“name”:“Karl”},{“id”:2,“name”:“Fritz”}]

但我想用单输出和输入字段显示(以及稍后处理)我的员工。我是一个血腥的初学者。对不起这个基本问题。愿有人想帮助我。谢谢你前进!!

我尝试了这个,但它无法正常工作:

export class Employee {
  id: number;
  name: string;
}

1 个答案:

答案 0 :(得分:0)

我们可以通过使用json管道以适当的方式显示json对象格式。 例如 -

component.ts->
obj = {
    a : 12,
    b : 123
  };

component.html
{{obj | json }}

{{3}}