2017-05-18 164 views
0

結合下面是我的局部分量代碼模板在角度4

.... 

.... 
ngOnInit() 
{ 

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

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

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

和下面是我的部分模板相關的代碼

{{ ajaxdata?.name }} 

在上述代碼打印的console.log語句「{」名稱」 :「約翰」}「如預期。 但{{ajaxdata?.name}}不打印「john」,任何想法可能是什麼原因?

+1

爲什麼會出現'''ajaxdata'後? –

+0

你可以給你的服務代碼嗎? – mcsekar

+1

@AgamBanga https://angular.io/docs/ts/latest/guide/template-syntax.html#!#safe-navigation-operator – mcsekar

回答

0

看起來你已經失去了this的背景。

在您的代碼中,this當前未指向您的類實例ajaxdata。有幾種方法可以解決這個問題。其中我認爲最簡單的方法是使用下面的箭頭功能:本

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

更多信息可以found here

0

我認爲這是

{{ajaxdata.?name }} 
+1

https://angular.io/docs/ts/latest/guide/template-syntax.html#!#safe-navigation-operator – mcsekar

2

你已經失去this上下文。

解決方案如下附:

方法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)) 

方式2:

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

    }) 

應該解決您的問題。