首页 > 解决方案 > 无法在 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 }}

标签: angularrestobservable

解决方案


看起来你得到的结果是嵌套数组,你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>

推荐阅读