我无法显示服务对象的内容。



我想在HTML组件上添加对象的变量,这些变量从服务中变成。我不能。

我的组件是:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { Profesional, ProfesionalService} from '../../profesional.service';

@Component({
selector: 'app-gestion-profesionales',
templateUrl: './gestion-profesionales.component.html',
styleUrls: ['./gestion-profesionales.component.css']
})
export class GestionProfesionalesComponent implements OnInit {
prof = new Array<Profesional>();
tags;

constructor(private profesionalService: ProfesionalService) { }
ngOnInit() {
this.allProf();
}
allProf(): void {
this.profesionalService.getProfesionales()
.subscribe(data => {
this.prof= data;
console.log(this.prof);
});
}
}

我的服务是:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';
export interface Profesional {
ID: number;
Name: string;
College: string;
DNI: string;
Surname: string;
Email: string;
Password: string;
Phone: string;
Photo: string;
}

const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class ProfesionalService {
private profesionalesUrl = 'https://h205.eps.ua.es:8080/profesionales';  // URL to web api
constructor(
private http: HttpClient
) { }
/** GET obtenemos todos los profesionales */
getProfesionales (): Observable<Profesional[]> {
return this.http.get<Profesional[]>(this.profesionalesUrl)
.pipe(
tap(profesionales => this.log(`fetched profesionales`)),
catchError(this.handleError('getProfesionales', []))
);
}
}

当我发出请求时,一切都很好。JSON响应如下:

Object results:
Array(35)
0: {ID: "1", DNI: "71955507F", College: "mimi", Name: "pepe", Surname: "popo", …}
1: {ID: "_09y4nb7b1", DNI: "434632tnm", College: "siuno", Name: "Matasanos", Surname: "Berenguer Pastor", …}

因此,我在HTML组件上显示信息时遇到了问题。我想用ngfor来做,但它不起作用。出现以下错误:找不到类型为"object"的不同支持对象"[object object]"。NgFor只支持绑定到数组等可伸缩对象。

<table>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Phone number</th>
<th>Email</th>
</tr>
<tbody>
<tr *ngFor="let item of prof">
<td>{{ item.Name }}</td>
<td>{{ item.Surname }}</td>
<td>{{ item.Phone }}</td>
<td>{{ item.Email }}</td> 
</tr>
</tbody>
</table>

可能是由于Profesional实例形成的变量prof。我不知道如何以正确的方式显示信息。

您从api得到的是JSON数组而不是Javascript对象,这就是为什么当Javascript尝试循环时会显示错误,因为您的尝试得到了一个您没有的对象。

使用JSON.parse((函数将其转换为JS对象。

更改这些线路

this.prof = data

带有

this.prof = JSON.parse(data);

所以它就像这个

ngOnInit() {
this.allProf();
}
allProf(): void {
this.profesionalService.getProfesionales()
.subscribe(data => {
this.prof = JSON.parse(data);
console.log(this.prof);
});
}

最新更新