我试图通过Angular显示json数据。但它显示的是整个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:
下面是我的REST控制器:
@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的解决方案,我必须使用{{t.t}}
根据您的代码,它应该是{{t.t}},而不是{{t.tname}}