问题描述: 在Angular 9中,一个service返回的列表包含数据,但是当使用*ngFor指令时,页面上不显示任何内容。
解决方法:
import { Component } from '@angular/core';
import { YourService } from 'your-service-path';
@Component({
selector: 'app-your-component',
template: `
{{ item }}
`,
})
export class YourComponent {
itemList: any[];
constructor(private yourService: YourService) {
this.itemList = [];
}
ngOnInit() {
this.getItemList();
}
getItemList() {
this.yourService.getItems().subscribe(
(data: any[]) => {
this.itemList = data;
},
(error) => {
console.log(error);
}
);
}
}
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class YourService {
constructor(private http: HttpClient) {}
getItems(): Observable {
return this.http.get('your-api-url');
}
}
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { YourService } from 'your-service-path';
@NgModule({
imports: [HttpClientModule],
providers: [YourService],
})
export class YourModule {}
请根据您的具体情况进行调整和修改。