0

I would like to display a list of items, retrieved from Firebase realtime database, on my page. My problem is that I need to parse JSON that I receive from Firebase and put it into an object so that I can call it from page.

export class Item { name: string, price: number }

Page code:

export class ItemsPage {

private itemsList; 
private userId;
private userFirebaseToken;

   constructor(public navCtrl: NavController,
          private userService: UserService) {} 



   this.userService.getItemsList(this.userId, this.userFirebaseToken)
                .subscribe(
                  items => this.itemsList = items,
                  error => console.log(error),
                  () => console.log('OK')
                );

}

Service code:

getItemsList(userId: string, userToken: string) {
    return this.http.get(this.userServiceUrl + userId + '/items.json?auth='+ userToken)
                    .map((response: Response) => response);

EDIT: Change the object into Array that can be called in ngFor directives. Now I have been getting [object Object]

Afeez Aziz
  • 1,337
  • 2
  • 12
  • 26
  • you can print the object in console with `console.log(JSON.stringify(your_object))` – Suraj Rao Mar 06 '17 at 12:38
  • @suraj , yes, I have the JSON object, but since it is from Firebase, it is like `{'someRandomID':{'name':'abc','price':'233'},'someRandomID2':{'name':'zxc','price':'987'}}` – Afeez Aziz Mar 06 '17 at 12:41
  • http://stackoverflow.com/questions/37431578/iteration-a-json-object-on-ngfor-in-angular-2 – Suraj Rao Mar 06 '17 at 12:52

1 Answers1

1

You can do it in your map function.It will send the parsed json to your subscribe

Try:

 .map((response: Response) => response.json());
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
  • When I do this, it will go to error, and console log error message as null – Afeez Aziz Mar 06 '17 at 08:38
  • That means you are getting null response. you need to check wether your firebase api is working correctly – Suraj Rao Mar 06 '17 at 08:41
  • I actually did. A console log at the service returns a full JSON when I use JSON.stringify. – Afeez Aziz Mar 06 '17 at 08:48
  • @AfeezAziz : Code Suraj posted is correct. May be your URL `this.userServiceUrl + userId + '/items.json?auth='+ userToken` is incorrect or returning nothing. If not, there is something not correctly happening in the flow. – Sagar Kulkarni Mar 06 '17 at 11:30
  • @sagarKulkarni and, yes I have been receiving an object. I have edited my question to reflect that I want to change this JSON to array to be used by the page. – Afeez Aziz Mar 06 '17 at 12:34