0

I'm new to Angular 6. I'm not getting how to access Json object values in view using key.

I'm making http.get(url) in my service and I'm calling that method in my component

export class CustomersComponent implements OnInit {

constructor(private accounts: AccountService) { }
account: Object;

ngOnInit() {
  this.accounts.getAccountById(1).subscribe((data)=> {
  this.account = data ;
}
);}}

The returned data is a json object is like this

{
 "accountId": 1,
 "attributeCode": "2300000000",
 "attributeLabel": "Customer Status"
 }

How to access the values inside this json object in view?

I have tried using

{{account.accountId}}

getting error in console as accountId undefined

   {{account | json}}

This is working fine, it is printing everything but I would like to use the values inside this object at different places in my view.

0

3 Answers 3

1

Access using [key] as follows,

{{account['accountId']}}
Sign up to request clarification or add additional context in comments.

2 Comments

Getting this error. TypeError: Cannot read property 'undefined' of undefined
you should enclose in quotes as its a string
0

To access values of correspondent key, do like this

{{account['accountId']}}

because accountId or key is string.

Comments

0

Maybe It's because your data is not loaded yet. I suggest put an div or ng-template before accessing it in template and if account is provided, then try to access it.like below:

<div *ngIf="account">
{{account['accountId']}}
</div>

or this:

{{account?.accountId}}

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.