Angular:返回 Observable 的正确方法是什么? [英] Angular: What's the correct way to return Observable?

查看:74
本文介绍了Angular:返回 Observable 的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法不正确:

  getProducts(): Observable<Product[]> {
      let PRODUCTS: Product[];
      this.http.get(this.base_url + "api/products")
      .subscribe(
        (data) => {
            for(var i in data) {
                PRODUCTS.push(new Product(data[i].id, data[i].name, data[i].category, data[i].description, data[i].price, data[i].amount));
            }
        },
        (error) => {
            console.log(error);
      });
      return of(PRODUCTS);
  }

我得到的错误是这样的:

The error I'm getting is this:

TypeError: Cannot read property 'push' of undefined

现在,我知道无法从 subscribe 函数中访问 PRODUCT 数组,但我无法获得正确的解决方案.

Now, I know that the PRODUCT array is not accessable from within the subscribe function, but I cannot get the correct solution for it.

谁能帮我解决这个问题.我想返回一个 Observable.

Can anyone help me with that. I want to return an Observable<Product[]>.

先谢谢你!

推荐答案

已更新以说明 API 似乎返回一个类似数组的对象而不是真正的数组这一事实.

Updated to account for the fact that the API seems to return an array-like object rather than a true array.

你想使用map:

getProducts(): Observable<Product[]> {
  return this.http.get(this.base_url + "api/products")
    .map(data => {
      let products = [];
      for (let i in data) {
        products.push(new Product(data[i].id, data[i].name, data[i].category, data[i].description, data[i].price, data[i].amount));
      }

      return products;
    })
    .do(null, console.log);
}

<小时>

由于@pixelbit 的评论尽管有误,但仍不断获得赞成票,以下是一个说明错误原因的示例:


Since @pixelbit's comment keeps getting upvotes despite being wrong, here's an example showing why it is wrong:

// Fakes a HTTP call which takes half a second to return
const api$ = Rx.Observable.of([1, 2, 3]).delay(500);

function getProducts() {
  let products = [];
  api$.subscribe(data => {
    for (let i in data) {
      products.push(data[i]);
    }
  });

  return Rx.Observable.of(products);
}

// Logs '[]' instead of '[1, 2, 3]'
getProducts().subscribe(console.log);

这篇关于Angular:返回 Observable 的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆