首页 > 解决方案 > 如何在 Angular 11 中的页面加载 Ajax 请求中传递 component.html 中的变量

问题描述

我已经制作了一个组件,并且在其中的 html 上我想要一个变量,其值来自ngOnInit.

问题是当我试图从我从 ajax 获得的对象中设置变量时给我undefined。可能是 ajax 调用在设置变量时仍在运行。我想问我如何设置变量。

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)
          )
  }

我也尝试将它放在构造函数中,但没有成功。

这是我想在 html 中获取变量的地方。

<div [ngStyle]="{'background-image': 'url(' + backgroundImagePath + ')'}">

标签: angularajaxtypescriptangular11

解决方案


HTTP 调用确实是异步的,不保证在执行下一行时完成。一个选项是在请求完成后构建 url:

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)
            )
    }
}

推荐阅读