这是我的代码示例,我正在尝试,并从我的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: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>https://stackoverflow.com/questions/61024020
复制相似问题