我有一个名为getPuzzle()的函数,它调用API来获取数据。我想用这些数据来修改一个div。问题是,这都是在构造函数中完成的,所以html还没有加载。
所以我把修改html的代码放入ionViewDidEnter中,然后它在调用API之前运行它丢失了数据this。puzzle
我如何不运行这段代码,直到HTML已经完全加载和API调用后?
ngOnInit() {
this.getPuzzle();
}
getPuzzle() {
//Get puzzle info
this.puzzlesService.getPuzzle().subscribe((data) => {
this.puzzleType = this.puzzlesService.puzzleType;
this.puzzle = this.puzzlesService.puzzle;
});
}
ionViewDidEnter() {
//Set first tab
if (this.puzzleType == 'text') {
new Vara("#text", "assets/fonts/vara/Satisfy/SatisfySL.json", [{
text: this.puzzle,
delay: 2000,
x: 2
}], {
fontSize: 25,
strokeWidth: 1.5,
duration: 15000,
color: "black"
});
}
}
快速解决方案
这是非常深入的尝试使用RxJS
命令式而不是装饰式(这是RxJS中相当主要的代码气味)。即便如此,这也是确保getPuzzle
中的this.puzzlesService.getPuzzle()
在//Set first tab
之后的代码运行之前发出的一种方法。
letsGooooooo = new ReplaySubject();
ngOnInit() {
this.getPuzzle();
}
getPuzzle() {
//Get puzzle info
this.puzzlesService.getPuzzle().subscribe((data) => {
this.puzzleType = this.puzzlesService.puzzleType;
this.puzzle = this.puzzlesService.puzzle;
this.letsGooooooo.next("GOOOOOOO!");
});
}
ionViewDidEnter() {
this.letsGooooooo.pipe(
take(1)
).subscribe(_ => {
//Set first tab
if (this.puzzleType == 'text') {
new Vara(
'#text',
'assets/fonts/vara/Satisfy/SatisfySL.json',
[
{
text: this.puzzle,
delay: 2000,
x: 2,
},
],
{
fontSize: 25,
strokeWidth: 1.5,
duration: 15000,
color: 'black',
}
);
}
});
}
More Involved Solution
修正你的服务,使puzzlesService
将当前的谜题和谜题类型作为一个可观察对象而不是属性。这样你就不需要在本地重新实现所有这些函数了。
ngOnInit() {
// No local version of puzzlesService needed
}
ionViewDidEnter() {
this.puzzlesService.getPuzzle().subscribe(puzzleData => {
//Set first tab
if (puzzleData.puzzleType == 'text') { // puzzleData.puzzleType instead of this.puzzleType
new Vara(
'#text',
'assets/fonts/vara/Satisfy/SatisfySL.json',
[
{
text: puzzleData.puzzle, // puzzleData.puzzle instead of this.puzzle
delay: 2000,
x: 2,
},
],
{
fontSize: 25,
strokeWidth: 1.5,
duration: 15000,
color: 'black',
}
);
}
});
}
您正面临生命周期问题。你能做的一个好方法是在Api的结果之后调用一个函数。在你看来,你可以使用询问来避免数据未准备好插入{{ puzzle?.text }}
ngOnInit(){
this.getPuzzle();
}
getPuzzle() {
//Get puzzle info
this.puzzlesService.getPuzzle().subscribe((data) => {
this.puzzleType = this.puzzlesService.puzzleType;
this.puzzle = this.puzzlesService.puzzle;
this.updateView(); 👈🏽
});
}
updateView() {
//Set first tab
if (this.puzzleType == 'text') {
new Vara("#text", "assets/fonts/vara/Satisfy/SatisfySL.json", [{
text: this.puzzle,
delay: 2000,
x: 2 }],{
fontSize: 25,
strokeWidth: 1.5,
duration: 15000,
color: "black"
});
}
}