2017-11-03 10 views
0

ajaxフェッチが完了した後にメソッドを呼び出すにはどうすればよいですか?フェッチが完了したときにメソッドを呼び出す方法

これはこれまでのコードですが、コールバックメソッドでthis.displayが見つかりません。

class fourViews { 
 
    static display(data){ 
 
    // Some stuff being displayed... 
 
    } 
 
    loadPage(){ 
 
    let url = "www.example.com"; 
 
    fetch(url).then(function(data) { 
 
    this.display(data); 
 
    }).catch(function(error) { 
 
     // If error.   
 
    }); 
 
    } 
 
}

答えて

1

あなたはそれがthis上で定義されることを期待してはいけませんので、あなたの方法displayは(とにかく、あなたの対象ではないと思われる)静的です。どこ静的な部分についての権利あなたは

fetch(url).then(function(data) { 
    fourViews.display(data); 
}) 

class fourViews { 
 
    static display(data){ 
 
    console.log('display called:\n', data.body); 
 
    } 
 
    loadPage(){ 
 
    let url = "https://jsonplaceholder.typicode.com/posts/1"; 
 
    fetch(url).then(function(response) { 
 
     // Note that the response object has methods to return promises to data, 
 
     // like json(): 
 
     response.json().then(function (data) { 
 
      fourViews.display(data); // static methods are not called on `this` 
 
     }) 
 
    }).catch(function(error) { 
 
     // If error.   
 
    }); 
 
    } 
 
} 
 

 
new fourViews().loadPage();

+0

:代わりにクラス名を使用します。しかしそれでもそれは見つけることができません。他の誰かが、数分前に次のように示唆していました。.then(data => {this.display(data);})。そのコードはうまくいく。 – Olof84

+0

テストURL付きの作業スニペットを追加しました。 'static'を削除してはいけません。それはOKと思われます。もちろん、それを削除すると 'this'で動作させることができますが、実際にはインスタンスとのリンクが不要なメソッドの場合に' static'を放棄するのはなぜですか? – trincot

関連する問題