[英]how to call a method in a class without this object in angular typescript
Hi friends I'm making an app which lists users's emails via Gmail API. 嗨,朋友们,我正在开发一个通过Gmail API列出用户电子邮件的应用程序。 For this I have a method which lists threads from user account and then messages in that threads gets fetched.
为此,我有一个方法列出了用户帐户中的线程,然后提取了该线程中的消息。 My function is as below:
我的功能如下:
public listThreads(opt_params){
gapi.client.load('gmail', 'v1', function(){
let request = gapi.client.gmail.users.threads.list({
'userId': 'me',
'q': opt_params
});
request.execute(function(response) {
$.each(response.threads, function() {
let thread_id = this.id;
this.getThread(thread_id, this.process_thread);
// error appears on above line. which says "this.getThread is not a function"
});
});
});
}
Error is "this.getThread is not a function". 错误是“ this.getThread不是函数”。 And that is because "this" now refers to response object and it does not refers to class members anymore.
这是因为“ this”现在是指响应对象,而不再是类成员。 But I need to call getThread function.
但是我需要调用getThread函数。 So I need to know if there is any other way to call class functions without this keyword?
因此,我需要知道是否有其他方法可以在没有此关键字的情况下调用类函数?
You cannot call a typescript method without using this
如果不使用
this
方法,则无法调用打字稿方法
Instead you should use fat arrow operators (=>)
at three places in your code as opposed to function
, to retain the context of this
. 取而代之的是,您应该在代码中与
function
相对的三个位置使用胖arrow operators (=>)
,以保留this
的上下文。
parameter of gapi.client.load()
gapi.client.load()
参数
gapi.client.load('gmail', 'v1', () => { ...... });
parameter of request.execute()
request.execute()
参数
request.execute((response) => { .... })
parameter of $.each $ .each的参数
$.each(response.threads, () => { let thread_id = this.id; this.getThread(thread_id, this.process_thread); // this should be accessible here });
Because the context, this
is lost in the callback. 因为上下文,
this
在回调中丢失。 Use arrow functions in typescript to preserve the context! 在打字稿中使用箭头功能可保留上下文!
request.execute().then((response)=> { // here you will have access to 'this' })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.