2017-09-15 69 views
-2

我目前剛學習Vue.js,並且遇到調用API的問題。我從https://swapi.co/api/people/訪問這個公共API,當我訪問電影細節時,我遇到了問題。我有電影數據,但數據堆積在最後一個數組中,我不知道該怎麼辦。希望你們能幫助我:dVue JS調用API的問題

<script> 
import axios from 'axios'; 

export default { 
    name: 'home', 
    data:() => ({ 
     profiles: [], 
     last_name_v: '', 
     movies_urls: [], 
     movies: [], 
     movie_s: [], 
     relateds: [], 
     errors: [], 
     datas: [] 
    }), 

    created() { 
     axios.get('https://swapi.co/api/people/') 
      .then(response => { 
       this.profiles = response.data.results.slice(0, 2); 
       for (var i = 0; i < this.profiles.length; i++) { 
        var profile_val = this.profiles[i]; 
        var full_name_o = profile_val.name; 
        var full_name_s = full_name_o.split(' '); 
        var last_name = full_name_s[full_name_s.length - 1]; 
        profile_val['last_name'] = last_name; 

        var movie_urls = profile_val.films.slice(0, 4); 
        console.log(profile_val.films.slice(0, 4)); 
        profile_val['movie_details'] = []; 
        for (var j = 0; j < movie_urls.length; j++) { 
         axios.get(movie_urls[j]) 
          .then(response => { 
           profile_val.movie_details.push(response.data); 
          }) 
          .catch(e => { 
           this.errors.push(e); 
          }); 
        } 
        this.datas.push(profile_val); 
       } 
      }) 
      .catch(e => { 
       this.errors.push(e); 
      }); 
    } 
} 

+0

後輸出以及 –

+0

澄清:「數據堆積在最後一個數組」中是什麼意思?什麼是「數據」?什麼是「最後一個數組」? –

回答

0

你怎麼看的profile_val值將是一旦所有的承諾,在你的內心for循環的決心?

for (var j = 0; j < movie_urls.length; j++) { 
    axios.get(movie_urls[j]) 
     .then(response => { 
      profile_val.movie_details.push(response.data); 
     }) 
     .catch(e => { 
      this.errors.push(e); 
     }); 
} 

一個你可以做最簡單的事情就是推動這一出到功能,並在封閉拍攝profile_val

function fetchMovieDetails (profile_val, movie_url) { 
    return axios.get(movie_url) 
     .then(res => profile_val.movie_details.push(res.data)); 
}