2017-05-28 19 views
0

この関数を使用して値を返すことはできません。外部変数をAxios外に設定する方法

getNameById (id) { 

    var name = '' 

    axios.get('/names/?ids=' + id) 
     .then(response => { 
     this.response = response.data 
     name = this.response[0].name 
     }) 
     .catch(e => { 
     this.errors.push(e) 
     }) 
    // Is empty 
    console.log('Name ' + name) 
    return name 
    } 

"then"内のname変数にアクセスして返しますか?

+0

をはい、それは私から – John

答えて

2

代わりに約束を返す必要があります。

getNameById (id) { 
    return axios.get('/names/?ids=' + id) 
     .then(response => { 
     this.response = response.data 
     return this.response[0].name 
     }) 
    } 

し、それを使用します。

getNameById(someId) 
    .then(data => { 
    // here you can access the data 
    }); 
+0

正しいアプローチ(1)を返しません! @OPの詳細についてはこちらをご覧くださいhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then – Christos

+0

Thanks @Christos! – Ioan

+0

あなたは大歓迎です! – Christos

関連する問題