1
votes

Service code which return json data

  export class EmployeeServiceService {
      constructor(private _http:Http) { }
      GetEmployees() :Observable<IEmployee[]>{
        debugger;
        return this._http.get("http://localhost:2724/api/employee/1")
        .map((response:Response)=> <IEmployee[]>response.json())
      }
    }

In this component class im not able to convert the json data please any one help me to solve my issue

export class EmployeeListComponent implements OnInit {

  Employees:IEmployee[];

      constructor( private _EmployeeService: EmployeeServiceService) { 

      }

      ngOnInit() {
       this._EmployeeService
        .GetEmployees().subscribe((employeeData)=> this.Employees = employeeData);
      }

    }

html

<tbody>
  <tr *ngFor="let employee of Employees">
    <td>{{employee.Address}}</td>
    <td>{{employee.City}}</td>
    <td>{{employee.EmployeeID}}</td>
    <td>{{employee.FirstName}}</td>
    <td>{{employee.LastName}}</td>
  </tr>
  <tr *ngIf="!Employees|| Employees.length== 0">
    <td>No employee to display!!!</td>
  </tr>
</tbody>

enter code here

1
can you post what is inside console.log(JSON.stringify(this.Employees)); - Sajeetharan
{"EmployeeID":1,"LastName":"Stein ","FirstName":"Nidprxmvtyjnat ","MiddleInitial":"D","SSN":"122-08-9952","Address":"Ap #461-7976 Enim. Street ","City":"Rutland ","State":"VT","Zip":"90400","Phone":"1-796-415-8913","Status":5,"Description":"This is sample data for the Employee Case Study. "} - Venkat subramaniyam
see the above is just an object. check my answer - Sajeetharan

1 Answers

0
votes

This error occurs whenever you are trying to bind an Object with ngFor. ngFor directive supports only arrays.

As per the request, it seems it returns only one Object,

 return this._http.get("http://localhost:2724/api/employee/1")

if you need to bind only one Object no need to use ngFor.

Also you need to initialize employees with an empty array.

Employees:IEmployee[] = [];

if you still want to bind one Object to the table, push the Object to the array as follows,

this.Employees.push(employeeData);

Two options

(i) Change your request to return all employees

 return this._http.get("http://localhost:2724/api/employee/all")

(ii) Push the Object to an array as follows,

ngOnInit() {
       this._EmployeeService
        .GetEmployees().subscribe((employeeData)=> this.Employees.push(employeeData);
      }