代码之家  ›  专栏  ›  技术社区  ›  Mohamed Wahshey

无法从API数据角度6绑定

  •  0
  • Mohamed Wahshey  · 技术社区  · 6 年前

    我正在使用api获取数据并将其绑定到html,我可以在控制台上显示响应,但是一旦我尝试将数据绑定到用户屏幕,我就不能显示任何内容

    我的HTML:

    <ul *ngFor="let item of items; let i of index">
     <li class="fa fa-plus">{{item.name}} - {{i}}</li>
    </ul>
    

    我的TS:

    id: number;
    name:string;
    imageUrl: string;
    items:any = {}; 
    ngOnInit() {
    this.getItems();
    }
    getItems() {
    this.getItemsService.getItems().subscribe(
      res => {
        console.log(res)
        if (res.Success) {
          this.items = res;
        }
      }
    )
    

    }

    我试图从一个对象数组中获取数据,这就是为什么我将项目定义为对象,如果我试图将它定义为一个数组,同样的结果,则无法将数据绑定到HTML。

    我的API链接:

    http://5a12745f748faa001280a746.mockapi.io/v1/stores/item

    任何问题或丢失的信息告诉我,但我需要帮助绑定这些数据

    1 回复  |  直到 6 年前
        1
  •  0
  •   Maryannah    6 年前

    两件事,首先是html: let i = index 是语法。

    第二个,你的绑定有一个条件:

    if (res.Success) {
      this.items = res;
    }
    

    这意味着你的回答有 Success 财产。

    我检查了你的api链接,但没有。

    所以在你的服务中,要么你用 Http from @angular/http HttpClient from @angular/common/http 是的。以下是两个语法:

    // Http
    return this.http.get('url').map(res => res.json());
    // HttpClient
    return this.http.get<any[]>('url');
    

    对于这种情况,请更改为以下内容,以检查是否有数据。你不需要检查是否成功,因为你有一个特殊的回调。这意味着你在有条件的地方总会成功的。

    if (res) {
      this.items = res;
    }