6

my service is like this

getRecords(): Observable<any>{
    return this.http.get(this.fetchAdminData)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

and Extract data is as following

private extractData(res: Response) {
    let body = res.json();
    return body || { };
  }

In my component i am calling this as follows

import {Component, OnInit} from '@angular/core'
import {FormsHandler} from '../services/service.forms'


@Component({
  selector: 'form-admin',
  templateUrl: '../partials/form5.html'
})

export class FormAdminComponent implements OnInit {
  public records
  constructor(private formHandler : FormsHandler){
  }

  ngOnInit(){
    this.formHandler.getRecords().subscribe(res => {
      if (res.ok){
        this.records = res.data
        console.log(res)
        console.log(this.records[0])
      }
    })
  }

}

But when this is called on as follows in html it errors

{{records}} // this is working perfectly 
    {{records[0]}}  //Cannot read property '0' of undefined ERROR CONTEXT:    [object Object]

also i even cannot access my nested object like this

<tr *ngFor="let record of records">
              <td>{{record.firstName + " "+ record.middleName+ " "+ record.LastName}}</td>
              <td>{{record.BankingDetails.company}} </td> // This results in errorTypeError: Cannot read property 'company' of undefined
              <td>{{record.BankingDetails}} </td> //working fine but resulting in [object Object]

              <td>Pending</td>
              </td>
            </tr>

results in TypeError: Cannot read property 'company' of undefined

my response is like this

Object {ok: true, data: Array[2]}

and complete data is like this :

[
 {
"Address": {
"addressLine1":  "nh" ,
"addressLine2":  "nghn" ,
"city":  "ngh" ,
"formStatus": 2 ,
"pinCode":  "ngh" ,
"state":  "nghn"
} ,
"BankingDetails": {
"bankName":  "csdcss" ,
"company":  "cd" ,
"designation":  "kn" ,
"loanAmount":  "csd" ,
"loanPurpose":  "cs" ,
"panCardNumber":  "84894848" ,
"salary":  "55"
} ,
"contact":  "vsd" ,
"date":  "vsd" ,
"dob": Mon Jan 01 1 00:00:00 GMT+00:00 ,
"email": abhishek@gmail.com, »
"firstName":  "cs" ,
"firstname":  "" ,
"formStatus": 3 ,
"gender":  "male" ,
"id":  "98fd72b9-62fe-4fcd-90d6-f2a5f83c052b" ,
"isAdmin": 1 ,
"lastName":  "vs" ,
"lastname":  "" ,
"middleName":  "vds" ,
"middlename":  "" ,
"month":  "vsd" ,
"password": <binary, 60 bytes, "24 32 61 24 31 30..."> ,
"username":  "" ,
"year":  "vs"
},
...
]

i did't getting what am i doing wrong becuase its working fine with console.log and printing a json but is not accessible with html

also i noted that when i am using

{{records}} 

its resulting in [object Object]

i have to explicitly write

{{records | json}}

to get my complete data

Hey please suggest me what i am doing wrong i want to access my nested elements like records.BankingDetails.company

Abhishek Soni
  • 1,677
  • 4
  • 20
  • 27

4 Answers4

13

You are fetching records async and when Angular tries to resolve bindings the first time records is still null therefore records[0] fails.

You can instead use

{{records && records[0]}}

For other expressions you can use the safe-navigation (Elvis) operator like

{{records?.someprop}}

but there is no safe-navigation for array index access (?[])

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
6

I finally got a solution to this problem as per @Akshay Rao suggestions i used these so that data is available before rendering of page

<div *ngIf="records">
</div>

also as per @Günter Zöchbauer suggestion i do require to use (Elvis) operator like

{{record.BankingDetails?.company}}

and it worked well . Thanks

Abhishek Soni
  • 1,677
  • 4
  • 20
  • 27
3

records initially is null and gets the value once the repsonse from the server comes

You should use

{{ records }}

{{records && records[0]}}
Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21
  • hey piyush explain me how to access my nested element like record.BankingDetails.company because{{records && records[0]}} is resulting in [object, Object] – Abhishek Soni Jul 17 '16 at 16:27
1
  1. if u are getting [object object] then u will have to first stringify the content and then parse that content like below...

var data = JSON.parse(JSON.stringify(records));

  1. If u are accessing your nested elements then you have 2 options for that too ... 2(a). either u can declare them as empty array or objects which is not a good idea but still it will help u ...
on initialization :-
records.bankingDetails = {};

2(b).The one which is approved by angular team is that u have to use a ngIf on top of your div where u are using the nested elements ..

this is all what u need :)

Akshay Rao
  • 3,454
  • 1
  • 15
  • 19
  • Thanks Akshay step 2(b) worked and i do get records[0] BUT strangely this also results in [object Object] i even used var data = JSON.parse(JSON.stringify(records)); but still i didnt get json there by resulting in error TypeError: Cannot read property 'company' of undefined when i use this {{record.BankingDetails.company}} but i do getting its value – Abhishek Soni Jul 17 '16 at 17:09
  • u mean u get this in ur console when u make a getrecords call ?? – Akshay Rao Jul 17 '16 at 17:16
  • yeah i used elvis operator and now its woring – Abhishek Soni Jul 17 '16 at 17:19
  • but i really need to know unlike angularjs why all these elvis things needs to be there in angular2 – Abhishek Soni Jul 17 '16 at 17:19
  • if u just want to see the data then u can just stringify it with JSON.stringify(records) in ur console... but if u want to access the values u need to parse them in objects ... no need of elvis bro ...i just tried stringify which gave me ur result which was before [object object] – Akshay Rao Jul 17 '16 at 17:23
  • i hope u got the answer for your question ... enjoy coding :) – Akshay Rao Jul 17 '16 at 17:52