【问题标题】:How do I display the Observable data I am getting from my api call using Angular?如何使用 Angular 显示从我的 api 调用中获得的 Observable 数据?
【发布时间】:2019-05-09 19:09:24
【问题描述】:

我对 Angular 很陌生,我正在尝试制作一个简单的应用程序来显示产品列表。我在 TS getProducts() 函数中调用了一个 api,它返回一个 observable,它是具有标题、艺术家、价格和 image_url 属性的产品列表。我正在尝试在我的页面中显示产品标题列表,但我正在努力让可观察的内容显示在 HTML 页面中。任何有用链接的帮助都会很棒。

这是我的打字稿:

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    products;

    constructor(private api: ApiService) {}  

    ngOnInit() {
        this.getProducts();
    }
    function
    getProducts() {
        return this.api.get("Products")
          .map((response: Response) => {
            var result = response.json();
            return result;
          });
    }
}

这是我的 HTML 模板:

<h1>Products</h1>
<div layout="row">
    <li ngclass="product" *ngFor="let product of products">
        {{product.title | json}}
    </li>
</div>

【问题讨论】:

    标签: angular observable


    【解决方案1】:

    getProducts 的返回值是 Observable 类型,你必须这样对待它。试试:

    <div layout="row">
        <li ngclass="product" *ngFor="let product of getProducts() | asnyc">
            {{product.title | json}}
        </li>
    </div>
    

    【讨论】:

      【解决方案2】:

      您的代码中有两个问题:

      1. Observables 仅在订阅时执行(在您的情况下,您只调用 map() - 这会向管道添加一个步骤,但实际上不会触发 observable 执行。

        李>
      2. 您永远不会为 products 赋值。

      我没有对此进行测试,但它可能看起来像:

      export class AppComponent implements OnInit {
          products: Product[];
      
          constructor(private api: ApiService) {}  
      
          ngOnInit() {
              this.getProducts().subscribe(result: Product[] => this.products = result);
          }
      
          getProducts() {
              return this.api.get("Products")
                .map((response: Response) => {
                  var result = response.json();
                  return result;
                });
          }
      }
      
      • 我冒昧地对您的属性应用了一些类型(并假设您的 api 请求返回了 Product 对象的列表 - 如果不是,只需删除类型或将其替换为 any)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-07
        • 2021-12-19
        • 1970-01-01
        • 2020-04-16
        • 2023-03-04
        • 2021-05-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多