如何在 Angular 11 中的页面加载 Ajax 请求中传递 component.html 中的变量
How to pass variable in component.html on page load Ajax request in Angular 11
我制作了一个组件,在 html 上我想要一个变量,其值来自 ajax 在 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 + ')'}">
Javascript 处理异步。请替换
ngOnInit() 与异步 ngOnInit()
this.getBackground() 等待 this.getBackground()
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)
)
}
}
我制作了一个组件,在 html 上我想要一个变量,其值来自 ajax 在 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 + ')'}">
Javascript 处理异步。请替换
ngOnInit() 与异步 ngOnInit() this.getBackground() 等待 this.getBackground()
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)
)
}
}