Angular: What's the correct way to return Observable?

萝らか妹 提交于 2021-02-11 13:38:33

问题


I have the following method which isn't working correct:

  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

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

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

Thank you in advance!


回答1:


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

You want to use 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);
}

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);


来源:https://stackoverflow.com/questions/48367939/angular-whats-the-correct-way-to-return-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!