数据成功显示在控制台中,但是在页面上显示时出现错误:
错误错误:尝试与'[object Object]'进行比较时出错。仅数组和 可迭代项允许的服务
getdetails(id:number) : Observable<INewsModule>{
return this._HttpClient.get<INewsModule>('http://localhost:1858/api/details/' + id)
}
组件
private items:any= [];
ngOnInit() {
let id : number = this._activeRoute.snapshot.params['id'];
this._NewsService.getdetails(id).subscribe(items =>{
this.items=items;
console.log(items);
} );
html
<table class="table">
<caption>List of users</caption>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">NameNews</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let details of items">
<th scope="col"> {{details.NameNews}}
</th>
</tr>
</tbody>
</table>
界面
export class INewsModule{
IDNews:number;
IDCategoery:number;
NameNews:string;
TopicNews:string;
DateNews?:Date;
ImageCaption:string;
ImageName:string ;
}
答案 0 :(得分:0)
看来,当您输入items
作为数组时,
该服务实际上返回的是单个对象。
也许您的服务返回的对象包含一个数组, 并且您需要执行以下操作:
this._NewsService.getdetails(id).subscribe(response => {
this.items = response.items;
console.log(this.items);
});
观看浏览器开发人员工具中的“网络”标签, 并查看JSON响应的样子。
答案 1 :(得分:0)
已解决
服务
getdetails(id:number): Observable <INewsModule[]>{
return this.http.get('http://localhost:1858/api/details/' +
id).map((response: Response)=><INewsModule[]>response.json());
}
组件
items : INewsModule[];
subscription: ISubscription;
statusMessage: string = 'please wait Loading data ... ';
.................
let id : number = this._activeRoute.snapshot.params['id'];
this._NewsService.getdetails(id).retryWhen((err) => {
return err.scan((retryCount) =>{
retryCount +=1;
if(retryCount < 6 ){
this.statusMessage ='Retrying .....Attept #' + retryCount;
return retryCount;
} else {
throw (err);
}
}, 0).delay(1000)
})
.subscribe((newsdata) => {
if(newsdata == null){
this.statusMessage = 'news does not exist';
} else {
this.items = newsdata
}
},
(error) =>{
this.statusMessage = "please try again after sometime"
console.log(error);
})
HTML
<table>
<thead>
<tr>
<th colSpan='2'>News Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<label class="label label-default">
Name news
</label> {{items.NameNews}}
</td>
</tr>
</tbody>
</table>