【发布时间】:2017-04-07 03:18:07
【问题描述】:
我正在使用 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 请求的异步性质有关。如果我设置一个字符串等于我想要的 url,然后在模板中指定它就可以正常工作。
TS 文件
bgURL: string = 'http://www.example.com/myImg.png';
模板
<!-- This works -->
<header [ngStyle]="{'background': 'url(' + bgURL + ')'}">
提前感谢您的帮助,这几天我一直在反对这个。
【问题讨论】:
标签: javascript angular