在这个段落下面的代码块中,您可以看到Twilio.Device.incoming,在这里,我将this.connection设置为conn。
@Injectable()
export class BaMsgCenterService {
public getData;
public incomingCall = false;
public connection;
constructor(private http: Http) {
this.initTwilio();
Twilio.Device.ready(function (device) {
self.incomingCall = true;
$(".card-title").text("Ready to receive incoming calls!");
});
Twilio.Device.incoming(function (conn) {
console.log(conn.status);
this.incomingCall = true;
this.connection = conn;
});
//other functions
}
}
}而不是我有一个组件类:
import {Component} from '@angular/core';
import { Http } from '@angular/http';
import {BaMsgCenterService} from './baMsgCenter.service';
@Component({
selector: 'ba-msg-center',
providers: [BaMsgCenterService],
styleUrls: ['./baMsgCenter.scss'],
templateUrl: './baMsgCenter.html'
})
export class BaMsgCenter {
public connection;
constructor(private _baMsgCenterService:BaMsgCenterService) {
this.connection = this._baMsgCenterService.connection;
}
pickup() {
this.connection.accept();
}
}在html代码中,我有一个(click)="pickup()"
但是,当我单击它时,它会说conn不存在。
inline template:63:10 caused by: Cannot read property 'accept' of undefined
我想要使拾取功能工作,它必须能够使用康涅狄格(或this.connection)在那个拾取功能。我认为Twilio.Device是稍后执行的(它是一个API).
发布于 2017-02-09 16:47:39
两位开发人员在这里传道。
在构造函数中设置this.connection = this_baMsgCenterService.connection时,不是将两个变量绑定在一起,而是将this.connection指向相同的位置(this.connection)。
下面是一个简单的例子:
var a, b;
a = b = "foo";
b = "bar";
console.log(a); // "foo";
console.log(b); // "bar";您需要继续引用消息中心服务的连接。您可以使用实例方法而不是属性来完成此操作。
类似于:
export class BaMsgCenter {
constructor(private _baMsgCenterService:BaMsgCenterService) {}
pickup() {
this.connection().accept();
}
connection() {
this._baMsgCenterService.connection;
}
}如果这有帮助的话请告诉我。
编辑
我仍然认为我回答了一半的问题,但关于事件中的this上下文的答案也是正确的。
发布于 2017-02-09 16:47:55
使用
(conn) => {而不是
function (conn) {还将function的所有其他出现形式更改为箭头函数样式,否则this.将不会像您预期的那样指向服务或compinent类。
发布于 2017-02-09 16:55:19
你搞错this了。当使用function语法时,this被动态绑定到调用的目标,也就是说,它绑定到作为方法调用函数的对象上。你有两个选择。
使用局部变量在闭包中使用的别名this:
var that = this;
takesAFunction(function (value) {
that.prop = value;
});如果您针对的是现代版本的NodeJS或现代浏览器,或者您可以访问一个广播程序;例如TypeScript、Babel或Traceur;只需使用ES2015箭头函数:
takesAFunction(value => {
this.prop = value;
});在箭头函数的内部,this是静态作用域,也称为词汇作用域,就像语言中的其他标识符一样。
第二种方法带来了更清晰的代码,在可用的地方应该是首选的。
https://stackoverflow.com/questions/42141987
复制相似问题