这是我的代码示例,我正在尝试,并从我的API端得到了响应,但无法通过*ngFor显示。在category-LIS.COMPOMENT.TS的ngOnInit中,我调用了服务并获取了数据。还有一件事是我在这里使用了容器。
//category.service.ts
getAll(): Observable<Response> {
return this.httpClient
.get<Response>(this.apiUrl + '/category/' + 1 + '/' + 10)
.pipe(catchError(this.errorHandler));
}
//category-list.component.ts
export class CategoryListComponent implements OnInit {
@Input() pageSize = 4;
categories: Category[] = [];
constructor(
public categoryService: CategoryService,
private changeDetectorRef: ChangeDetectorRef
) {}
ngOnInit() {
this.categoryService.getAll().subscribe((data:Response) => {
this.categories = data.data;
console.log(this.categories);
});
}
}
//category-list.component.html
<p>Category List</p>
<ul>
<li *ngFor="let data of categories">{{data.id}}</li>
</ul>
//category.component.html
<div class="card-body">
<app-category-list></app-category-list>
</div>
//data

发布于 2020-04-04 13:16:45
在有角度的美元符号($)标记中可以观察到。当你完成这项任务时
this.categories$ = data.data; // jsonObj as Category[];您指定的是可观察对象的结果,而不是可观察对象本身。因此,在这种情况下,要么删除HTML中异步管道并重命名categories$ -> categories,这样就不会产生误导,还可以将类型更改为仅Category[],或者在组件中指定categories$,如下所示
this.categories$ = this.categoryService.getAll();发布于 2020-04-04 13:19:02
试着在html中输出这个变量,看看你首先得到了什么。
你的代码逻辑大体上看起来是正确的,除了关于可观察性的那部分(我不是专家)。尝试进行这些更改
categories: Category[] = [];
this.categoryService.getAll().subscribe((data) => {
this.categories = data.data;
});
<ul>
<li *ngFor="let data of categories">{{data.id}}</li>
</ul>发布于 2020-04-04 15:07:21
这是一个正在运行的stackblitz演示,它从一个API中获取数据,将结果分配给一个类的属性,并在模板中使用*ngFor显示结果。
Fork我的demo,如果你的代码仍然不能工作,请通过提供一个可重现的demo让我们进一步知道。
值得一提的是,您应该将import { BrowserModule } from '@angular/platform-browser';包含在AppModule的imports数组中,而您可能已经拥有了。
https://stackoverflow.com/questions/61024020
复制相似问题