2017-08-24 62 views
0

我想調用一個Web API與jquery $ ajax()函數,在進行調用後我不會將結果存儲在我的打字稿變量中,但我沒有想到如何做到這一點。訪問打字稿內的jQuery變量

$.ajax({ 
    method: "POST", 
    url: 'URL', 
    data: { email:'[email protected]', 
     password:'pass'} 

}) 
.done(function(msg) { 

    this.response=msg; 

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

在ajax調用之外聲明變量並將結果存儲在那裏。 –

+0

@Our_Benefactors uhm ..不... –

+0

'這不是你想象的那樣,即使是這樣,做你正在做的事情也不會奏效。您需要使用承諾$ .ajax返回。 –

回答

0

如果你想設置的對象使Ajax調用,您可以使用箭頭功能來捕捉上下文這

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

只要你使用的是打字稿,你可以利用異步並等待簡化您的代碼。這將是等效的:

class MyCaller { 
    response: any; 
    async doCall() { 
     try { 
      this.response = await $.ajax({ 
       method: "POST", 
       url: 'URL', 
       data: { email:'[email protected]', password:'pass'} 
      }) 
     }catch(error) { 
      this.response = error 
     } 
    } 
} 
+0

它完美的作品 – daliDV

+0

很高興聽到:) –