utils.js,checkAccess方法裏,axios請求去查詢用戶權限,在then裏面去返回response的數據。
然後在其他模塊調用這個方法: var result = checkAccess(UIItems.AdminMenu)
,但是拿不到返回值,一直說是undefined…
想了好久,都沒有意識到,axios請求是異步的,請求一旦發送出去,瀏覽器就會繼續執行後面的代碼,那會兒根本還沒有得到server的response呢…
害…腦子那會兒可能是凍住了
import axios from "axios"
export function checkAccess(uiElement){
axios.get("/api/someurl/checkPermission ", {
params: { uiElement }
})
.then(res => {
return res.data;
})
.catch(err => {
console.log(err);
return false
});
}
把checkAccess方法改一下,直接返回axios.get()…,也就是一個Promise對象,然後在調用的地方去拿返回值。
import axios from "axios"
export function checAccess(uiElement){
return(axios.get("/api/someurl/checkPermission ", {
params: { uiElement }
}));
}
checkAccess(UIItems.AdministrationMenu)
.then(res => {
if (res.data === true) {
// do something if user has access to admin menu
}
})
.catch(err => {
console.log(err);
});
另外做一個記錄,供日後參考(push和pop好說,但是總分不清unshift 和 shift)
//add elements into the array from beginning
this.menuArray.unshift(Admin, Statistic);
//return and delete the 1st element of array
this.menuArray.shift();