我的Angular版本是16.0.1,我尝试从API获取数据
https://dummy.restapiexample.com/api/v1/employees
这是我的型号
export interface Emploee {
employee_name: string;
}
我的服务是
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Emploee } from '../models/emploee.model';
@Injectable({
providedIn: 'root'
})
export class EmploeeService {
_url = "https://dummy.restapiexample.com/api/v1/employees"
constructor(private http:HttpClient) { }
getEmploee():Observable<Emploee[]>{
return this.http.get<Emploee[]>(this._url)
} }
而我的component.ts是
import { Component } from '@angular/core';
import { Emploee } from '../models/emploee.model';
import { EmploeeService } from '../services/emploee.service';
@Component({
selector: 'app-emploee',
templateUrl: './emploee.component.html',
styleUrls: ['./emploee.component.scss']
})
export class EmploeeComponent {
emploee$! : Emploee[];
ngOnInit() {
this.fetchEmploee();
}
constructor(private emploeeService:EmploeeService){}
fetchEmploee(){
this.emploeeService.getEmploee().subscribe(res=> this.emploee$ = res);
}
}
这是我的component.html
<p *ngFor="let emploee of emploee$">{{emploee.employee_name }}</p>
当我运行我的项目我得到这个错误
找不到类型为“object”的不同支持对象“[object Object]”。NgFor only >支持绑定到可迭代对象,例如数组
我该怎么解决呢?我的项目也在这个链接中:https://stackblitz.com/edit/stackblitz-starters-xuvgju?embed=1&file=src%2Fmain.ts
Postman的照片是:
1条答案
按热度按时间kqlmhetl1#
首先,通常我们使用
$
前缀来表示Observable。您在数组上使用它,这会让查看您代码的其他人感到困惑。我以为你错过了异步管道,因为我认为emploee$变量是一个可观察的。
但实际问题是返回的数据不是您定义的形状。
如果您查看数据形状,它包含的数据比
Emploee
数据多得多。考虑更新界面以匹配数据形状。
或者,您可以修改
getEmploee
,以便只访问“data”属性,该属性似乎包含实际的员工数据。我有一个工作Stackblitz在这里:https://stackblitz.com/edit/stackblitz-starters-5uprkt
有关RxJS的更多信息,请查看此视频:https://youtu.be/vtCDRiG__D4