【问题标题】:access a jquery variable inside typescript访问打字稿中的jquery变量
【发布时间】:2018-02-02 20:34:12
【问题描述】:

我正在尝试使用 jquery $ajax() 函数调用 Web api,在调用后我不会将结果存储在我的 typescript 变量中,但我不知道该怎么做。

 $.ajax({
  method: "POST",
  url: 'URL',
  data: { email:'test@gmail.com',
      password:'pass'}

})
.done(function(msg ) {

  this.response=msg;

}) .fail(function(msg) {
  this.response=msg;
})

【问题讨论】:

  • 在 ajax 调用之外声明一个变量并将结果存储在那里。
  • @Our_Benefactors 嗯.. 不...
  • this 不是你想象的那样,即使是这样,做你正在做的事情也不会奏效。您需要改用承诺 $.ajax 返回。

标签: jquery angularjs typescript ionic-framework


【解决方案1】:

如果您想在进行 Ajax 调用的对象上设置它,您可以使用箭头函数来捕获上下文 this

class MyCaller {
   response: any;
   doCall() {
      $.ajax({
         method: "POST",
         url: 'URL',
         data: { email:'test@gmail.com', password:'pass'}
     }).done((msg ) => {
       // this refers to MyCaller, with a simple function it would not
       this.response=msg; 
     }).fail((msg) => {
       this.response=msg;
     })     
   }
}

只要您使用 TypeScript,您就可以利用 async 和 await 来简化您的代码。这将是等效的:

class MyCaller {
    response: any;
    async doCall() {
        try {
            this.response = await $.ajax({
                method: "POST",
                url: 'URL',
                data: { email:'test@gmail.com', password:'pass'}
            })
        }catch(error) {
            this.response = error
        }
    }
}

【讨论】:

  • 很高兴听到 :)
猜你喜欢
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 2021-03-08
  • 1970-01-01
  • 2017-05-21
  • 2023-04-04
相关资源
最近更新 更多