如何打印JSON值,我像angular一样很基础,请有人帮助我。
test.html
{{ projects }}
<li *ngFor="let obj of projects">{{obj | json }}</li>
服务.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);
}
组件.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"
]
我尝试过,出现错误:ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor只支持绑定可迭代对象(例如数组)。
显示这种错误。
extractData
方法中,Array.isArray(body)
是什么意思?此外,也许是你的客户端在捣乱。你在服务中使用的是 HttpClient 还是 Http?如果是 HttpClient,它应该已经给你 JSON(尽管在你的代码中看起来并不像)。 - Zlatko