1

I am trying to extract an object from database using observable. after I retrieve the object and put it inside a variable, I can only get the whole object into my template and as soon as I try to access any specific field of the object I get an error.

Here is my service which has a function that returns an observable with the type that I want. It basically looks in the database and returns a list of Item objects that their URL is equal to my URL variable:

  getItemByUrl(url : string):Observable<Item[]>{
    return this.angularFire.database.list('items',{query:{
        orderByChild: 'url',
        equalTo: url}
    })

Now, in my main component I use this function to take the list and then I put the first item of the list into my own item object, so I can use it in my own program:

ngOnInit(){


   this.itemService.getItemsByUrl(this.url)
    .subscribe(res => this.item = res[0])
}

Now I pass my item to the template with:

{{item | json}}

and everything is fine and I see the whole object. But as soon as I try to access on of the fields in the item such as {{item.name}} I get the error:

Cannot read property 'name' of undefined

any ideas why?

Farhad
  • 115
  • 1
  • 7
  • 2
    Because `item.name` is only available once `item` is; the JSON pipe is designed to tolerate that. – jonrsharpe Feb 01 '17 at 22:51
  • 5
    Possible duplicate of [Observable type error: cannot read property of undefined](http://stackoverflow.com/questions/34734671/observable-type-error-cannot-read-property-of-undefined) – jonrsharpe Feb 01 '17 at 22:52

1 Answers1

0

I was finally able to find the issue. As jonrsharpe mentioned, apparently the value you get from the observable is just a Json. so I had to make a function that gets the json and creates new Item from it. Then I can use the Item object and refer to its properties. Here is the function I used:

 static fromJson({$key, name,number}){

    return new Item($key, name,number)}
Farhad
  • 115
  • 1
  • 7