【发布时间】:2018-04-05 00:30:31
【问题描述】:
我有如下 JSON 响应。我想要做的是低于 JSON 响应进入我的 angular2 应用程序。但我无法获得预期的输出。请就我的编码解决方案发表意见。
{
"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"
}
}
此数据应显示在我的 department.component.html 文件中
<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>
这是我的 department.component.ts 文件(我可以在没有任何错误的情况下获得 Member found 警报)
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();
}
}
这是我调用后端服务的staff.service.ts文件
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;
}
);
}
}
控制台输出
这是我调用前端 Angular2 应用程序的后端控制器 (Laravel 5.4)。
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);
}
【问题讨论】:
-
请您发表完整的回复好吗?
-
对不起,我没有抓住你。我已经发布了所有的代码示例
-
能否请您发布console.log(response.json().department);的输出
-
请发布 json 响应
-
它不是从 Postman JSON 响应中看到的数组
标签: arrays json angular angular2-directives