2017-08-14 25 views
0

我試圖從localforage獲得一個axios調用的值,但它不起作用。Vue.js Axios從本地存儲獲取價值(localforage)返回承諾對象而不是價值

axios.get('https://api.example.org/api/?uname=' + this.$getItem('LSuname'), { 
    withCredentials: true, 
    headers: {'Authorization': 'Bearer ' + this.$getItem('LSmytoken')} 
}) 

我在控制檯得到一個403錯誤與此:

XHR加載失敗:GET 「https://api.example.org/api/?uname=[object%20Promise]」。

我自己也嘗試this.$getItem('LSuname').then(value => { return value })this.$getItem('LSuname').then(function (value) { return value })但我得到完全相同的403和不良網址並承諾在年底

我能夠正確地沒有問題,其他地方在我VUE返回值,如下所示:

this.$getItem('LSuname').then(value => { 
    console.log('uname:' + value) 
}) 

回答

0

貌似this.$getItem是一個異步調用,將返回一個Promise。這意味着您必須等待該調用完成後才能調用任何取決於這些異步調用的返回值的代碼。

在你的情況,你可以使用Promise.all()等待所有的異步調用的製作axios.get調用之前返回:

let unamePromise = this.$getItem('LSuname'); 
let mytokenPromise = this.$getItem('LSmytoken'); 

Promise.all([unamePromise, mytokenPromise]).then((vals) => { 
    axios.get('https://api.example.org/api/?uname=' + vals[0], { 
    withCredentials: true, 
    headers: {'Authorization': 'Bearer ' + vals[1] } 
    }) 
}) 
+0

,進行了它的工作,謝謝! – Stephen

+0

以類似的方式(也許?)我不能從本地存儲獲取簡單的值,只顯示在我的頁面上,任何指針? (我曾嘗試將它設置爲一個計算值,一種方法,試圖向數據中添加諸如'fullname:this。$ getItem('LSfullname')'之類的東西,但沒有任何效果。 – Stephen

+0

就像我所說的,'this。$ getItem ()'總是要返回一個Promise,如果你設置'fullname'等於'this。$ getItem('LSfullname')',那麼'fullname'將是Promise,而不是異步函數的結果。在這裏閱讀Promise:https://developers.google.com/web/fundamentals/getting-started/primers/promises – thanksd