2017-04-20 95 views
0

JSON字符串在我angular2組件我怎樣才能在angular2

keyword_test={}; 

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

} 

的console.log(數據)和執行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打印「對象{}」我認爲沒有任何對象。 keyword_test是否被錯誤地初始化了? 當我在getData函數中打印console.log(typeof數據)時,結果是字符串... 我確實將它更改爲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(); 
     }); 
    } 

}

+0

手動鍵入keyword_test將正常工作。 –

回答

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); 
});