-1
我想通過Angular顯示json數據。但它顯示的是整個json數據而不是特定的數據。如何在角度版本2.4.10中顯示JSON數據
情況1:
import { Component, OnInit } from '@angular/core';
import { HttpService } from 'app/http.service';
import { Response } from '@angular/http/src/static_response';
@Component({
selector: 'app-httpapp',
template: `
<p>
httpapp Works!
<br><hr>
{{t_obj | json}}
</p>
<div *ngFor="let t of t_obj">
{{t.tname}}//not working
{{t}}
</div>
`,
})
export class HttpappComponent implements OnInit {
t_obj : T ;
constructor(private httpService : HttpService) { }
ngOnInit()
{
this.httpService.getData()
.subscribe(
(data : Response) => {
this.setData(data)
}
);
}
setData(response : Response)
{
this.t_obj = response.json();
console.log(response.json());
}
}//class
class T{
tname : string;
}
輸出:
[ { "t": "A" }, { "t": "B" }, { "t": "C" } ]
[object Object]
[object Object]
[object Object]
{{t.tname}},此片段的代碼表示什麼都沒有。
下面是我的服務器端代碼:
@RestController
public class NewClass
{
@RequestMapping("/greeting")
public List greeting()
{
List l = new ArrayList();
l.add(new T("A"));
l.add(new T("B"));
l.add(new T("C"));
return l;
}
}//public class NewClass
class T
{
public String t;
public T(String t)
{
this.t = t;
}
}
現在我想知道我怎麼可以只顯示數據,而不是完整的JSON對象。
案例2:
下面是我的休息控制器:
@RequestMapping("/greeting")
public T greeting()
{
return new T("Done..!");
}
角碼:
@Component({
selector: 'app-httpapp',
template: `
<p>
httpapp Works!
<br><hr>
{{t_obj.t}}
</p>
`,
})
export class HttpappComponent implements OnInit {
t_obj : any ;
constructor(private httpService : HttpService) { }
ngOnInit()
{
this.httpService.getData()
.subscribe(
(data : Response) => {
this.setData(data)
}
);
}
setData(response : Response)
{
this.t_obj = response.json();
console.log(response.json());
console.log(this.t_obj.t);
}
}//class
對於情況下,兩個我得到了以下錯誤消息:
EXCEPTION: Uncaught (in promise): Error: Error in ./HttpappComponent class HttpappComponent - inline template:3:14 caused by: Cannot read property 't' of undefined
Error: Error in ./HttpappComponent class HttpappComponent - inline template:3:14 caused by: Cannot read property 't' of undefined
示出此錯誤信息後,將其打印在下面的行:
{t: "Done..!"}
Done..!
所以我的問題是,根據錯誤消息,如果「T」是未定義則接着如何被打印在控制檯日誌。
更新:我得到的解決方案的情況下1,我必須使用{{TT}}
角哪個特定的verion? –
根據您的代碼,我認爲它應該是{{t.t}} –
我的角度版本是2.4.10 –