我如何在Angular中使用基于对象的json数据

问题描述 投票:1回答:2

//Employee service starts
import {
  Injectable
} from "@angular/core";
import {
  HttpClient,
  HttpErrorResponse
} from "@angular/common/http";
import {
  IEmployee
} from "../interfaces/employee";
import {
  Observable
} from "rxjs/Observable";
import "rxjs/add/operator/catch";
import "rxjs/add/observable/throw";

@Injectable()
export class EmployeeService {
  private _url: string = "assets/data/employee.json";
  constructor(private http: HttpClient) {}
  getEpmloyees(): Observable < IEmployee[] > {
    return this.http.get < IEmployee[] > (this._url).catch(this.errorHandler);
  }

  errorHandler(error: HttpErrorResponse) {
    return Observable.throw(error.message || "Server Error");
  }
}
//Employee service end

//-------**********-------*********------**********-------

//Employee component starts
@Component({
  selector: "app-employee-details",
  templateUrl: "./employee-details.component.html",
  styleUrls: ["./employee-details.component.scss"]
})
export class EmployeeDetailsComponent implements OnInit {
  public employees = [];
  public errorMsg;

  constructor(private _employeeService: EmployeeService) {}

  ngOnInit() {
    this._employeeService.getEpmloyees().subscribe(
      data => ((this.employees = data),
        error => (this.errorMsg = error)
      );
    }
  }
  //Employee component ends
<p>{{errorMsg}}</p>
<table border="1">
  <tr>
    <th>ID</th>
    <th>NAME</th>
    <th>AGE</th>
    <th>Mobile</th>
    <th>Action</th>
  </tr>

  <tbody *ngFor="let employee of employees">
    <tr>
      <td>{{employee.id}}</td>
      <td>{{employee.name}}</td>
      <td>{{employee.age}}</td>
      <td>{{employee.mob}}</td>
      <td><button>Delete</button></td>
    </tr>
  </tbody>
</table>

<!--Used JSON data
[
  { "id": 1, "name": "sam", "age": 25, "mob": 9996663752 },
  { "id": 2, "name": "adward", "age": 26, "mob": 9124563712 },
  { "id": 3, "name": "yoshi", "age": 27, "mob": 9246663012 },
  { "id": 4, "name": "casie", "age": 29, "mob": 967663012 }
]
-->

<!-- This data through items object I want to use in above code
{
  "items": [
    { "id": 1, "name": "harry", "age": 33, "mob": 3476643752 },
    { "id": 2, "name": "jorge", "age": 54, "mob": 7845633712 },
    { "id": 3, "name": "timon", "age": 65, "mob": 9753833012 },
    { "id": 4, "name": "simon", "age": 43, "mob": 8547763012 }
  ]
}
-->

上面是我的员工服务代码和员工的组件,它们工作正常,因此在这里我也共享了有关如何使用第二个JSON数据(位于第一个JSON数据以下)以及基于“ items”对象的JSON数据。所以我处于一种状况,我需要进行哪些更改才能获取基于对象的JSON数据。

// Employee服务开始从“ @ angular / core”导入{可注入};从“ @ angular / common / http”导入{HttpClient,HttpErrorResponse};从“ ../ interfaces / ...

json angular object service angular8
2个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.