2017-04-06 34 views
0

我正在使用Angular 2,並且無法將數據從api調用渲染到我的模板中。我張貼了我的組件和模板的一個簡短例子。Angular 2無法渲染API調用的數據

TS文件

import { Component, OnInit } from '@angular/core'; 
import { GlobalDirective } from '../../../global.directive'; 

export class MainInfoComponent implements OnInit { 

constructor(public globalDirective: GlobalDirective) {} 

logURL() { 
    //returns undefined 
    console.log(this.globalDirective.bgURL); 

} 

ngOnInit() { 
    this.logURL(); 
} 
} 

this.globalDirective.bgURL是IMG URL的字符串,我們會說http://www.example.com/myImg.png

的GlobalDirective文件使得坐在S3到一個JSON文件的調用並返回img鏈接和其他東西,我試圖在模板中呈現。我知道正確的數據正在返回,因爲我可以在控制檯中看到它。

模板

<p>{{globalDirective.bgURL}}</p> <!-- This works --> 
<header [ngStyle]="{'background': 'url(' + globalDirective.bgURL + ')'}"> <!-- Returns undefined --> 

我試圖弄清楚爲什麼我可以呈現在P標籤內globalDirective.bgURL,但如果我嘗試呈現它作爲一個標題樣式或登錄它ngOnInit它返回undefined。

我認爲這個問題可能與JSON請求的異步性質有關。如果我設置一個字符串等於我想要的網址,然後在模板中指定它工作正常。

TS文件

bgURL: string = 'http://www.example.com/myImg.png'; 

模板

<!-- This works --> 
<header [ngStyle]="{'background': 'url(' + bgURL + ')'}"> 

在此先感謝您的幫助,一直打我的頭這一個了幾天。

回答

1

它應該是,

<header [ngStyle]="{'background': 'url(' + globalDirective.bgURL + ')'} "> 
+0

哎呦。是的,我想我在嘗試通過這種方式進行嘗試。我確定並回去編輯我原來的問題。我仍然困惑,爲什麼我的logURL()函數返回undefined。 –