簡體   English   中英

Angular 2無法通過API調用呈現數據

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM