我如何在angular2中获得字符串json

时间:2017-04-20 04:53:55

标签: json angular

在我的angular2组件中

keyword_test={};

getData() {
    this.service.getData()
        .subscribe(
            data => {
                this.keyword_test = data
                console.log(data);
                console.log(this.keyword_test);
            });

}

console.log(data)和console.log(this.keyword_test)打印这样的数据

                {
                    "caption": "folder0",
                    "type": "folder",
                    "subnodes": [
                        {
                            "caption": "folder1",
                            "type": "folder",
                            "subnodes": [
                                {
                                    "caption": "keyword1",
                                    "type": "keyword",
                                    "search_filter_expression": "sfe1"
                                },
                                {
                                    "caption": "keyword2",
                                    "type": "keyword",
                                    "search_filter_expression": "sfe2"
                                }
                            ]
                        },
                        {
                            "caption": "folder2",
                            "type": "folder",
                            "subnodes": [
                                {
                                    "caption": "keyword3",
                                    "type": "keyword",
                                    "search_filter_expression": "sfe3"

                                },
                                {
                                    "caption": "keyword4",
                                    "type": "keyword",
                                    "search_filter_expression": "sfe4"

                                }
                            ]
                        }
                    ]
                }

但在我的ngOnInit

 ngOnInit() {
    this.getData();
    console.log(this.keyword_test);
}

尽管this.getdata(),this.keyword_test print" Object {}"我认为没有任何对象。 keyword_test是否初始化不正确? 当我在getData函数中打印console.log(typeof data)时,结果是字符串... 我确实在服务中将其更改为json,但我不知道为什么。

++,这是我的服务

@Injectable()
export class keywordService {
    private API_URI: string = 'MYAPIURL';

    constructor(private http: Http) {
    }

    getData() {
        return this.http.get(this.API_URI, {body: ""})
            .map(res => {res.json();
        });
    }

}

1 个答案:

答案 0 :(得分:0)

 ngOnInit() {
    this.getData(); // this execute but data arrives with call back
    console.log(this.keyword_test); //this execute before data has arrived and thats why it is not printing the result from success call
}

正确的方式

this.service.getData()
   .subscribe(
       data => {
          this.keyword_test = data
          console.log(data);
          console.log(this.keyword_test);
});