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 + ')'}">
在此先感谢您的帮助,一直打我的头这一个了几天。
哎呦。是的,我想我在尝试通过这种方式进行尝试。我确定并回去编辑我原来的问题。我仍然困惑,为什么我的logURL()函数返回undefined。 –