angular - 如何在 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 + ')'}">
解决方案
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)
)
}
}
推荐阅读
- jenkins - 如何将输入值传递给计划的 Jenkins 管道作业?
- asp.net - 无法从前端 UMBRACO-8 中隐藏导航项目
- node.js - 在 Moodle 中使用 NodeJS 模块
- javascript - 如何检查 CK Editor 是否有使用 JS/jQuery 的输入?
- tensorflow - 神经网络如何对只有一个密集层和 RELU 的图像进行分类?
- javascript - Angularjs 多个 HTTP POST 请求导致 net::ERR_INSUFFICIENT_RESOURCES
- jquery - 如何使用 yajra Datatable 在表格中显示堆栈条形图 foreach 行?
- html - Blazor,新布局索引
- dictionary - 使用脚本字典在 MS Access 中存储对象以避免循环引用并允许表单知道其所有者对象
- javascript - tsconfig 不能使用 commonjs 作为节点的 mondule 设置