0

Below is my partial component code

....

....
ngOnInit() 
{

this.service.getData().subscribe( function(data) {

    try 
    {
      console.log(JSON.stringify(data)); // {"name":"john"}
      this.ajaxdata = data;
}
catch(err) 
{
   console.log('Error Here....');
}

        });
}
....
....

and below is my partial template related code

{{ ajaxdata?.name }}  

console.log statement in the above code prints "{"name":"john"}" as expected. But {{ ajaxdata?.name }} does not print "john" , any idea what could be the reason ?

4
  • 1
    why is there ? after ajaxdata? Commented May 18, 2017 at 9:58
  • can you give your services code ? Commented May 18, 2017 at 9:59
  • 1
    @AgamBanga angular.io/docs/ts/latest/guide/… Commented May 18, 2017 at 10:01
  • Ahhh! Didn't know that in angular2 :) Commented May 18, 2017 at 10:03

3 Answers 3

2

You have lost this context.

Solutions are attached below:

Way 1:

this.service.getData().subscribe( function(data) {
    try {
        console.log(JSON.stringify(data)); // {"name":"john"}
        this.ajaxdata = data;
    }
    catch(err) {
        console.log('Error Here....');
    }

}.bind(this))

Way 2:

this.service.getData().subscribe( (data) => {
        try {
            console.log(JSON.stringify(data)); // {"name":"john"}
            this.ajaxdata = data;
        }
        catch(err) {
            console.log('Error Here....');
        }

    })

It should resolve your issue.

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

Comments

0

It looks like you have lost the context of this.

In your code, this is currently not pointing to your class instance of ajaxdata. There are a couple of ways to fix this. The easiest of which I believe is to use an arrow function as below:

this.service.getData()
  .subscribe(data => this.ajaxdata = data)

More information on this can be found here

Comments

0

I think it is

{{ajaxdata.?name }}

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.