【发布时间】:2018-06-09 19:55:29
【问题描述】:
如何打印 json 值,我很像 angular,请有人帮帮我。
test.html
{{ projects }}
<li *ngFor="let obj of projects">{{obj | json }}</li>
services.ts
getProjects(): Promise<Addtimesheet[]> {
return this.http.get("http://192.168.1.90/EMS/api/TimeSheetAPI/getProjects")
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
console.log("Sdfsdfsdfsd sss");
console.log(body);
return body;
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
component.ts
import { Component, OnInit } from '@angular/core';
import { Addtimesheet } from './addtimesheet';
import { TimesheetService } from './timesheet.service';
import { Projects } from './projects';
@Component({
selector: 'app-timesheet',
templateUrl: './timesheet.component.html',
styleUrls: ['./timesheet.component.css'],
providers: [TimesheetService]
})
export class TimesheetComponent implements OnInit {
timesheet = {};
today: any;
private projects: Projects[] = [];
private errorMessage: any = '';
constructor(private timesheetService: TimesheetService) {
}
ngOnInit() {
this.timesheetService.getProjects()
.then(projects => this.projects = projects)
console.log(this.timesheetService.getProjects());
}
}
json 值
[
"AESEMS",
"ChainDrive",
"CICAND",
"CICAPI",
"CICiOS",
"CICWeb",
"KC_APPTV",
"KCMagento",
"RDLSWeb",
"Riddles",
"TB",
"TBAND",
"TBiOS",
"TestProject"
]
我试过了,错误错误:找不到“对象”类型的不同支持对象“[对象对象]”。 NgFor 只支持绑定到 Arrays 等 Iterables。
显示某种错误。
【问题讨论】:
-
请显示整个component.ts文件。
-
@szmitas 更新了component.ts
-
可能后端意外没有发送promise:在你的服务中,
extractData方法,Array.isArray(body)说什么?另外,也许你的客户在惹你。您在服务中使用 HttpClient 还是 Http?如果是 HttpClient,它应该已经为您提供 JSON(尽管在您的代码中看起来不像)。 -
你确定你的服务返回一个数组吗?
-
对我来说真的听起来你没有得到一个数组。请检查开发工具中的响应选项卡并将其复制粘贴到您的问题:)