angular - 无法在 Angular 中显示从服务到 html 视图的返回数据。
问题描述
在我的 angular2 应用程序中,我尝试使用 Github 服务并尝试在 UI 上显示返回数据。
在第一次尝试中,我收到一个错误,因为“找不到类型为 'object' 的不同支持对象 '[object Object]'。”我想出了错误的原因并创建了一个自定义管道来将对象转换为数组,但我仍然是无法将数据绑定到 UI。
服务代码:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable,of } from 'rxjs'
export interface GitHubUser
{
html_url:string;
avatar_url:string;
login:string;
score:string;
}
@Injectable({
providedIn: 'root'
})
export class MyserviceService {
constructor(private _http:HttpClient) { }
getGitHubData(_searchTerm):Observable<GitHubUser[]>{
return this._http.get<GitHubUser[]>
("https://api.github.com/search/users?q="+_searchTerm);
}
}
管道代码
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'derp' })
export class DerpPipe {
transform (value, args) {
return Array.from(value);
}
}
应用组件.ts
constructor(private _obj:MyserviceService){//(private _githubService:GitHubServiceService1){
this.data$= this._obj.getGitHubData('gaurav');
this.data$.subscribe(users=> {
this.users=users;
console.log(this.users);
});
.html 文件
*ngFor="let user of users | derp"
{{ user.score }}
解决方案
看起来你得到的结果是嵌套数组,你ngFor
应该看起来像这样,
<ul *ngFor="let user of users">
<li>
<ul *ngFor="let info of user.items">
<li>{{info | json}}</li> //here you can access properties
</li>
</ul>
推荐阅读
- mysql - 如何从每列中删除重复项并仍将所有数据保留在 mysql 中?它可能吗?请帮忙
- django - 为一对多关系编写 django 查询,(django 查询和 taggit)
- python - 为列名添加空格
- javascript - 我想在几秒钟后执行 JavaScript 代码
- azure - Service Fabric:System.IndexOutOfRangeException -“System.RA”报告属性“ReplicaOpenStatus”的警告
- excel - 电源查询连接刷新时的消息框
- php - DataTables Jquery File Export 没有显示按钮
- razor - 出现错误“未定义索引:razorpay_payment_id”
- amazon-web-services - 当我们创建 AWS eks 集群时,管理工作节点的主节点在哪里?
- html - 如何仅使用 CSS 添加位于标题文本下方一半的颜色条?只用颜色填充 div 的下半部分?