1

I have service and method getCategory() for get category from server. Method is :

getCategory(): Observable<CategoryModel[]> {
    return this.http.get<CategoryModel[]> (this.productUrl)
        .pipe(
            catchError(this.handleError('getHeroes', []))
        );
}

In my component I want store data in list categoryList: CategoryModel[]; with method

getCategory(): void {
        this.dataStorageServiceService.getCategory()
            .subscribe(
                (cateogrys: CategoryModel[]) => {
                    this.categoryList = cateogrys;
                    console.log(this.categoryList)
                }
            }

And in outputcategoryList enter image description here is Object, and I can not render on the template.

4
  • Are you using Firebase? Commented Oct 31, 2018 at 9:39
  • Yes. I using Firebase. Commented Oct 31, 2018 at 9:40
  • Object.values? Commented Oct 31, 2018 at 9:42
  • With firebase you will get objects and not arrays. for more info: firebase.googleblog.com/2014/04/… Commented Oct 31, 2018 at 9:42

3 Answers 3

4

Since you are getting the object instead of an Array. You have two options, either you convert your Object to Array or use KeyValuePipe in the html template -

 <div *ngFor="let category of categoryList | keyvalue">
      {{category.key}}:{{category.value}}
  </div>

For more info visit - https://github.com/angular/angular/blob/master/CHANGELOG.md#610-beta1-2018-06-13

Sign up to request clarification or add additional context in comments.

Comments

2

With firebase you will get objects and not arrays. for more info: https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html

So one solution is to "convert" the object to an array when you fetch it in your service:

return this.http.get<CategoryModel[]> (this.productUrl)
  .pipe(
    map(products => {
      return Object.values(products);

      // OR

      return Object.keys(products).map((keyName) => {
        return {id: keyName, product: products[keyName]};
      });
    }),
    catchError(this.handleError('getHeroes', []))
  );

1 Comment

Object.values(products); is supper cleaner than KeyValuePipe
0

You can also use this ,

categoryList : CategoryModel[] = [];

And then you can push the user object and make as a array,

this.categoryList .push(<<the data you want to push>>);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.