2017-06-06 161 views
0

我正在研究一個nuxt js/vue js項目。其中我必須調用多個REST API。在頁面組件中,我調用asyncData()nuxt js API來調用REST api。Nuxt Js asyncData返回值的行爲奇怪。

import { getCategories } from '~/api' 
import { getProducts } from '~/api' 


export default { 

data() { 
    return { 

    } 
},` 



asyncData ({ req, params }) { 
//-----------------PART 1----------------------------- 
    // var res1 = getCategories() 
    // var res2 = getProducts() 

    // return { 
    // res1, 
    // res2 
    // } 
//-----------------PART 2----------------------------- 
    // return getCategories() 
    // return getProducts() 


//---------------------------------------------- 
     }, 



created() { 

    if(typeof(Storage) !== "undefined"){ 

     if(!localStorage.getItem("cityName")){ 
     this.$router.push('/') 
     } 

    } else{ 
     console.log('This browser does not support local storage') 
    } 

    this.$store.dispatch('initFilters') 


    this.$store.dispatch('initCategories', this.categories) 

    //NOTICE HERE 
    // console.log(this.allProducts) //This one works on single return 
    // console.log(this.res1.allProducts) //This doesnot work on object return 

    }, 

} 

當我嘗試回報getCategories()回報的getProducts()(PART 2中的代碼),它的工作原理,並返回我想要的對象的結果。

但正如我需要兩個對象,我試圖把它們放在一個對象,並返回它們(第1部分)然後通過的console.log(this.res1.allProducts)我沒有得到期望的對象調用。

這裏是API代碼

import axios from 'axios' 
const API_ROOT = 'http://deligram.mg/rest/' 
const API_VERSION = 'V1' 
const MAGENTO_STORE = 'default' 
const API_BASE = API_ROOT + '/' + MAGENTO_STORE + '/' + API_VERSION + '/' 

const apiUrl = (path) => { 
    return API_BASE + path 
} 

const apiGet = (path) => { 
    return axios.get(apiUrl(path)) 
} 

export function getCategories() { 
    return apiGet('categories') 
    .then((res) => { 
    return { categories: res.data } 
    }) 
} 

export function getProducts() { 
    return apiGet('products?searchCriteria%5BcurrentPage%5D=10') 
    .then((res) => { 
    return { allProducts: res.data } 
    }) 
} 

誰能告訴我,我究竟做錯了什麼?或者任何人都可以提出另一種方法在單一回報中獲得兩個對象?

回答

1

我假設你的API方法返回一個Promise。您應該使用Promise.all等到兩個承諾都解決了,然後返回一個所有數據對象nuxt應該設置:

var res1 = getCategories() 
var res2 = getProducts() 
return Promise.all(re1, res2).then(function ([data1, data2]) { 
return Object.assign({}, data1, data2) 
}) 

生成的對象將是這樣的:

{ 
    categories: [ /* data from getCategories() */] 
    allProducts: [ /* data from getProducts() */ ] 
} 
+0

出現此錯誤:返回Object.assign({},data1,data2) 錯誤:模塊構建失敗:SyntaxError:return是保留字 – ZIS

+0

哦,這是我的一個錯字。編輯我的帖子。 –

+0

謝謝。我想你有一些錯字錯誤。我固定它btw。這個概念是100%正確的。 } return Promise.all([res1,res2])。then(value => { return Object.assign({},value [0],value [1]) }) ' – ZIS