TypeScript Store Parse 查询结果
TypeScript Store Parse Query result
我有以下代码
export class AppComponent implements OnInit {
public guests: any[] = [];
constructor(private apiService: ApiService) {
}
ngOnInit(): void {
this.apiService.getAllGuestsQuery().find({
success(results) {
for (let i = 0; i < results.length; i++) {
const object = results[i];
console.log(object.get('companyName'));
}
},
error(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
}
}
getAllGuestsQuery
returns一个Parse.Query
对象。我想将结果存储在我的客人数组中。例如。做类似 this.quests = results
的事情
但是我无法访问成功方法中的 this.guests class 变量。
我该怎么做?
您可以尝试在 ngOnInit()
方法的开头将对 this
的引用传递到单独的变量中。类似于 let that = this;
。稍后在您的回调中通过 that
参考 this
(class 实例)。
export class AppComponent implements OnInit {
public guests: any[] = [];
constructor(private apiService: ApiService) {
}
ngOnInit(): void {
let vm = this;
this.apiService.getAllGuestsQuery().find({
func(r){ vm.guests } // will be available
});
}
}
这是因为当您将 {} 构造传递给 find() 函数时,会在那里创建一个新范围。如果你使用 ES6 箭头语法你可以做得更好(但是我写起来很麻烦,你必须以完全不同的方式处理错误,最好是承诺)
我有以下代码
export class AppComponent implements OnInit {
public guests: any[] = [];
constructor(private apiService: ApiService) {
}
ngOnInit(): void {
this.apiService.getAllGuestsQuery().find({
success(results) {
for (let i = 0; i < results.length; i++) {
const object = results[i];
console.log(object.get('companyName'));
}
},
error(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
}
}
getAllGuestsQuery
returns一个Parse.Query
对象。我想将结果存储在我的客人数组中。例如。做类似 this.quests = results
的事情
但是我无法访问成功方法中的 this.guests class 变量。
我该怎么做?
您可以尝试在 ngOnInit()
方法的开头将对 this
的引用传递到单独的变量中。类似于 let that = this;
。稍后在您的回调中通过 that
参考 this
(class 实例)。
export class AppComponent implements OnInit {
public guests: any[] = [];
constructor(private apiService: ApiService) {
}
ngOnInit(): void {
let vm = this;
this.apiService.getAllGuestsQuery().find({
func(r){ vm.guests } // will be available
});
}
}
这是因为当您将 {} 构造传递给 find() 函数时,会在那里创建一个新范围。如果你使用 ES6 箭头语法你可以做得更好(但是我写起来很麻烦,你必须以完全不同的方式处理错误,最好是承诺)