[英]Angular 2 can't render data from API call
I am using Angular 2 and having trouble rendering data from an api call into my template. 我正在使用Angular 2,并且无法将api调用中的数据呈现到模板中。 Ill post a short example of my component and template.
病态的发布了我的组件和模板的简短示例。
TS file 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 is a string of an img url, we'll say http://www.example.com/myImg.png this.globalDirective.bgURL是img网址的字符串,我们会说http://www.example.com/myImg.png
The GlobalDirective file makes a call to a JSON file sitting on S3 and returns img links and other things I am trying to render in the template. GlobalDirective文件对坐在S3上的JSON文件进行调用,并返回img链接和我尝试在模板中呈现的其他内容。 I know the correct data is being returned because I can see it in the console.
我知道会返回正确的数据,因为我可以在控制台中看到它。
Template 模板
<p>{{globalDirective.bgURL}}</p> <!-- This works -->
<header [ngStyle]="{'background': 'url(' + globalDirective.bgURL + ')'}"> <!-- Returns undefined -->
I am trying to figure out why I can render globalDirective.bgURL
within the P tags, but if I try to render it as a header style or log it in ngOnInit it returns undefined. 我试图弄清楚为什么可以在P标签中呈现
globalDirective.bgURL
,但是如果我尝试将其呈现为标头样式或将其记录在ngOnInit中,它将返回未定义的内容。
I think the issue may be something to do with the async nature of the JSON request. 我认为问题可能与JSON请求的异步性质有关。 If i set a string equal to the url I want, and then specify that in the template it works fine.
如果我设置的字符串等于我想要的网址,然后在模板中指定它可以正常工作。
TS file TS文件
bgURL: string = 'http://www.example.com/myImg.png';
Template 模板
<!-- This works -->
<header [ngStyle]="{'background': 'url(' + bgURL + ')'}">
Thanks in advance for any help, been beating my head against this one for a few days. 预先感谢您提供的任何帮助,几天来一直困扰着我。
它应该是,
<header [ngStyle]="{'background': 'url(' + globalDirective.bgURL + ')'} ">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.