如何在Typescript中的回调中访问类变量
How to access class variable in callback in Typescript?
这是我当前的代码:
import {Page} from 'ionic-angular';
import {BLE} from 'ionic-native';
@Page({
templateUrl: 'build/pages/list/list.html'
})
export class ListPage {
devices: Array<{name:string, id: string}>;
constructor() {
this.devices=[];
}
startScan (){
this.devices = []; // This "this" exists and works fine
BLE.scan([],5).subscribe(
(device)=>{
if(device.name){
this.devices.push({name:device.name,id:device.id}); // this.devices does not exists
}
},
(err) => {
console.log(JSON.stringify(err));
}
);
}
connectToDevice(device){
BLE.connect(device.id).subscribe(success=>{
console.log(JSON.stringify(success));
});
}
}
当调用startScan函数时,我正试图将返回的设备推送到阵列,但this.devices不可用。我试过保存这个,但还是没有成功。有人能帮我理解我缺了什么吗?
更新:设置
var self = this;
在startScan()的顶部,然后在.subscribe回调中使用它就是答案!
this.devices不可用
一个常见的问题。将startScan
更改为箭头功能:
startScan = () => {
this.devices = [];
BLE.scan([],5).subscribe(
(device)=>{
if(device.name){
this.devices.push({name:device.name,id:device.id}); // this.devices does not exists
}
},
(err) => {
console.log(JSON.stringify(err));
}
);
}
更多
https://basarat.gitbook.io/typescript/future-javascript/arrow-functions
这是我的代码,它通过按钮点击事件将字符添加到html文本区域。
HTML
<div class="console-display">
<textarea [(ngModel)]="textAreaContent" name="mainText"></textarea>
<div class="console-keys">
<button (click)="getKeyInput($event)" name="key01" type="button" value="1">1</button>
<button (click)="getKeyInput($event)" name="key02" type="button" value="2">2</button>
</div>
</div>
TS
export class HomeComponent {
tempString = "64";
getKeyInput(event){
let self = this;
manageTextArea(self, event.target.value, this.textAreaContent);
}
}
function manageTextArea(self , ch : string, textArea : string): void {
if (checkCharacter_Number(ch)){
self.textAreaContent += ch;
}
console.log(self.tempString);
}
它运行良好。
相关文章:
- 查询后websql成功回调无法访问变量
- 访问通过XHR.onreadystatechange回调中的XHR.send(data)发送的数据
- jQuery post,访问responseType或回调中的响应
- 在jQuery中,我如何从$.ajax回调函数访问$(this)
- 如何处理在javascript中访问数据结构的两个回调
- 如何在Typescript中的回调中访问类变量
- 如何访问ng-init或ng-checked中服务回调函数中声明的$scope变量
- 可以't从回调函数内部访问响应
- 如何在Promise回调中访问实例变量
- 如何通过回调访问nodejs中的mongodb计数结果
- 回调访问数据
- 如何从回调访问成员变量
- 从回调访问对象的属性
- 如何从传入的预定义回调访问外部变量
- 从 topic.subscribe's 回调访问小部件
- Javascript从另一个回调访问对象变量,而不将变量放在全局范围内
- 如何从WebSocket回调访问React中的组件方法
- 当使用原型方法声明从回调访问对象时,如何访问对象的其他方法
- js回调访问Angular作用域
- 从XMLHttpRequest onload回调访问全局变量