0

I have made a component and on html of that i want to have a variable, whose value is coming from ajax response in ngOnInit.

Problem is when i am trying to set the variable from object which is i am getting from ajax is give me undefined. May be ajax call is still running while it sets the variable. I want to ask how i can set the variable.

export class mainPage implements OnInit {
    public backgroundData: any;
    public backgroundImagePath : string = '';
  constructor(private $state: StateService, private MyService : MainServicesService) {
  }

ngOnInit(): void {
      this.getBackground();
      console.log(this.backgroundData);
      this.backgroundImagePath = environment.BaseUrl+this.backgroundData.folder+this.backgroundData.file;
  }

getBackground(){
      let client = this.client_id;
      this.MyService.getClientInfo(client)
          .subscribe(
              (data) => {
                  this.backgroundData  = data;

              } ,
              error => console.log(error)
          )
  }

I have also tried to put it in the constructor but no success.

Here is where i want to get the variable in html.

<div [ngStyle]="{'background-image': 'url(' + backgroundImagePath + ')'}">
programmer
  • 115
  • 1
  • 2
  • 12

2 Answers2

1

The HTTP call is indeed asynchronous and is not guaranteed to be finished when the next line is executed. An option would be to build the url when the request has finished:

export class mainPage implements OnInit {
    public backgroundData: any;
    public backgroundImagePath: string = '';

    constructor(private $state: StateService, private MyService: MainServicesService) {
    }

    ngOnInit(): void {
        this.loadBackground();

    }

    loadBackground() {
        let client = this.client_id;
        this.MyService.getClientInfo(client)
            .subscribe(
                (backgroundData: any) => {
                    this.backgroundImagePath = environment.BaseUrl + backgroundData.folder + backgroundData.file;
                },
                error => console.log(error)
            )
    }
}
MaartenDev
  • 5,631
  • 5
  • 21
  • 33
-1

Javascript work on asynchronous. Please replace

ngOnInit() with async ngOnInit() this.getBackground() with await this.getBackground()

Vicky Kumar
  • 239
  • 7
  • 21