2017-08-24 14 views
0

私はJavaScriptを使ってWeb APIを呼び出そうとしていますが、呼び出し後に私のtypescript変数に結果を格納することはできませんでしたが、 。typescript内の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 .. no ... –

+0

「これはあなたが思うものではなく、たとえそれがあったとしても、あなたがしていることをやってもうまくいかないでしょう。代わりにpromise $ .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

嬉しい:) –

関連する問題