[英]Angular 2 can't render data from API call
我正在使用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网址的字符串,我们会说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中,它将返回未定义的内容。
我认为问题可能与JSON请求的异步性质有关。 如果我设置的字符串等于我想要的网址,然后在模板中指定它可以正常工作。
TS文件
bgURL: string = 'http://www.example.com/myImg.png';
模板
<!-- This works -->
<header [ngStyle]="{'background': 'url(' + bgURL + ')'}">
预先感谢您提供的任何帮助,几天来一直困扰着我。
它应该是,
<header [ngStyle]="{'background': 'url(' + globalDirective.bgURL + ')'} ">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.