【问题标题】:Angular 2 can't render data from API callAngular 2 无法从 API 调用中呈现数据
【发布时间】: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


    【解决方案1】:

    应该是,

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

    【讨论】:

    • 哎呀。是的,我想我在解决这个问题时尝试过。我会确保并返回并编辑我原来的问题。我仍然对为什么我的 logURL() 函数返回 undefined 感到困惑。
    猜你喜欢
    • 2021-02-23
    • 2023-03-30
    • 1970-01-01
    • 2017-08-14
    • 2017-07-21
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 2018-10-28
    相关资源
    最近更新 更多