简体   繁体   中英

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. Ill post a short example of my component and template.

TS file

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

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. 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.

I think the issue may be something to do with the async nature of the JSON request. If i set a string equal to the url I want, and then specify that in the template it works fine.

TS file

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 + ')'} ">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM