从api提取的数据未显示在屏幕上,但我正在控制台中获取数据。
data.service.ts
const httpOptions = {
headers:new HttpHeaders({'Content-Type':'application/json'})
};
@Injectable()
export class DataService {
constructor(private http: HttpClient) {}
getuserdetails(){
return this.http.get<any>
('http://jsonplaceholder.typicode.com/users/1')
.pipe(map(item => {
return item;
}));
}
}
information.component.ts
export class InformationComponent implements OnInit {
dataItem:any = {}
constructor(private data: DataService) {
this.data.getuserdetails().subscribe(item=>{
console.log(item);
this.dataItem=item;
});
}
ngOnInit() {
}
}
information.component.html
<div *ngIf="dataItem?.length>=0">
<div *ngFor='let x of dataItem'>
{{x.name}}
</div>
</div>
在这里,我正在控制台中获取用户1的详细信息,但未在主屏幕上显示。
答案 0 :(得分:2)
尝试将代码放入ngOnInit
ngOnInit(){
this.data.getuserdetails().subscribe(item=>{
console.log(item);
this.dataItem=item;
});
}
并通过