Search code examples
arraysjsonangularangular2-directives

How to get JSON array response data in angular2 application


I have JSON response like below. What I want to do is get below JSON response into my angular2 application. but I couldn't get the expected output. Kindly give opinions about my coding solution.

{
"staffinfo": {
    "id": 3,
    "DeptID": 2,
    "OfficeID": 3,
    "FirstName": "Loreiya",
    "LastName": "Cheng",
    "DOB": "1991-04-02",
    "IsWorking": 1,
    "created_at": "2017-10-22 13:07:15",
    "updated_at": "2017-10-22 13:07:15"
},
"officeinfo": {
    "id": 3,
    "Name": "Finance-Payroll ",
    "Address": "No 20/1, Cross street, dalas, Block A ",
    "Description": "staff salary division ",
    "created_at": "2017-10-24 00:00:00",
    "updated_at": "2017-10-24 00:00:00"
}

}

this data should display in my department.component.html file

 <form #f="ngForm" (ngSubmit)="onSubmit(f)">
  <div class="form-group">
   <label for="depid">Department</label>
    <select name="depid" id="depid" class="form-control" ngModel>
      <option value="1">HR</option>
      <option value="2">Finance</option>
      <option value="3">Marketing</option>
    </select>
  </div>
  <button type="submit" class="btn btn-primary">Search</button>
</form>

<div *ngFor="let dep of department">
  {{ dep.staffinfo }}
</div>

this is my department.component.ts file (I could get Members found alert without any errors)

import { Component, OnInit, Input } from '@angular/core';
import { NgForm } from "@angular/forms";
import { StaffService } from "../staff.service";
import { Department } from "../department.interface";

@Component({
  selector: 'app-department',
  templateUrl: './department.component.html',
  styleUrls: ['./department.component.css']
})
export class DepartmentComponent implements OnInit {
@Input() department: Department[];

  constructor(private staffService: StaffService) { }

  ngOnInit() {
  }

  onSubmit(form: NgForm) {
    this.staffService.getDept(form.value.depid)
    .subscribe(
      () => alert('Members found')
    );
    form.reset();
  }
}

this is my staff.service.ts file to call back-end service

import { Injectable } from "@angular/core";
import { Http, Response, Headers } from "@angular/http";
import 'rxjs/Rx';
import { Observable } from "rxjs";

@Injectable()
export class StaffService{
  constructor(private http: Http) {
  }

getDept(depid: number): Observable<any>{
    return this.http.get('http://127.0.0.1:8000/api/dept/' + depid)
    .map(
      (response: Response) => {
        return response.json().department;
      }
    );
  }
}

console ouput

enter image description here

Postman JSON response enter image description here

this is my backend controller (Laravel 5.4) to call front-end Angular2 application.

    public function getDeptinfo($id)
   {
     $staffinfo = Staff::find($id);

     if($staffinfo){
         $officeinfo = Office::find($staffinfo['OfficeID']);
     }

     $response = [
         'staffinfo' => $staffinfo,
         'officeinfo' => $officeinfo
     ];

     return response()->json($response, 200);
   }

Solution

  • You need to assign reposnse to the department :

    Service :

    getDept(depid: number): Observable<any>{
        return this.http.get('http://127.0.0.1:8000/api/dept/' + depid)
        .map((response: Response) => response.json());
      }
    }
    

    Replace your DepartmentComponent with this :

    export class DepartmentComponent implements OnInit {
        department: Department;
    
        constructor(private staffService: StaffService) { }
    
        onSubmit(form: NgForm) {
            this.staffService.getDept(form.value.depid).subscribe((res) => {
                this.department = res;
            });
            form.reset();
        }
    }
    

    Template side

    Replace this :

    <div *ngFor="let dep of department">
      {{ dep.staffinfo }}
    </div>
    

    With :

    {{ department?.staffinfo | json }}