2017-12-18 106 views
-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}}

+0

角哪个特定的verion? –

+2

根据您的代码,我认为它应该是{{t.t}} –

+0

我的角度版本是2.4.10 –

回答

2

按你的代码,它应该是{{TT}},而不是{{t.tname}}