Typescript/Angular7不允许我更改变量值
在my home.page.ts中,我定义了一个变量,在执行回调函数后,该变量的值会随之变化。但是当我想再次使用它时,在我的代码中,它有默认值。例如:Typescript/Angular7不允许我更改变量值,angular,typescript,Angular,Typescript,在my home.page.ts中,我定义了一个变量,在执行回调函数后,该变量的值会随之变化。但是当我想再次使用它时,在我的代码中,它有默认值。例如: export class Home implements OnInit { test_value = 'a'; constructor(){ //Here I call a function automatically which I expect a //callback function to handle the response.
export class Home implements OnInit {
test_value = 'a';
constructor(){
//Here I call a function automatically which I expect a
//callback function to handle the response.
}
myCallbackFunction(result){
this.test_value = 'b';
}
//Later I push a button to do some action
myButton() {
console.log(this.test_value); // displays 'a' even I changed
// the value in my callback
}
}
如何正确分配值?在控制台上打印之前调用该函数
export class Home implements OnInit {
test_value = 'a';
constructor(){
//Here I call a function automatically which I expect a
//callback function to handle the response.
}
myCallbackFunction(){
this.test_value = 'b';
}
//Later I push a button to do some action
myButton() {
this.myCallbackFunction();
console.log(this.test_value); // displays 'b'
}
}
传递回调时,使用或右箭头函数保留此
请参阅:第24行和第26行如何传递myCallbackFunction()?这可能会更改其内部的
此。你能从构造器中包含更多省略的代码吗?换句话说,我怀疑这正在发生,威廉,这正是我的观点。这行代码解决了我的问题:My3rdPartLib.doWithCallback(This.myCallbackFunction.bind(This));没有人会知道,我只是碰巧猜到,您应该有更完整的代码示例。我不认为OP希望在用户单击按钮时调用myCallbackFunction()
,而是在某个异步操作完成时调用。