2017-02-22 62 views
1

我正在为次要项目构建单页应用程序。我一直在尝试将API调用的数据保存到对象中的电影数据库中。如果我console.log对象,我可以看到它的所有属性和值。如果我console.log object.property,它返回'未定义'。这是代码:对象属性未定义,对象本身显示所有数据虽然

(() => { 
"use strict" 

    /* Saving sections to variables 
    --------------------------------------------------------------*/ 
    const movieList = document.getElementsByClassName('movie_list')[0]; 
    const movieSingle = document.getElementsByClassName('movie_single')[0]; 

    /* All standard filters for displaying movies 
    --------------------------------------------------------------*/ 
    const allFilters = { 
    trending: 'movie/popular', 
    toplist: 'movie/top_rated', 
    latest: 'movie/now_playing', 
    upcoming: 'movie/upcoming' 
    }; 

    const allData = {}; 

    /* Initialize app - Get al standard data and save it in object 
    --------------------------------------------------------------*/ 
    const app = { 
    init() { 
     getData(allFilters.trending, 'popular'); 
     getData(allFilters.toplist, 'toplist'); 
     getData(allFilters.latest, 'latest'); 
     getData(allFilters.upcoming, 'upcoming'); 

     this.startPage(); 
    }, 
    startPage() { 
     window.location.hash = "trending"; 
    } 
    } 

    /* Function for getting data from the API 
    --------------------------------------------------------------*/ 
    const getData = (filter, key) => { 
    const request = new XMLHttpRequest(); 
    const apiKey = '?api_key=xxx'; 
    const getUrl = `https://api.themoviedb.org/3/${filter}${apiKey}`; 

    request.open('GET', getUrl, true); 
    request.onload =() => { 
     if (request.status >= 200 && request.status < 400) { 
     let data = JSON.parse(request.responseText); 
     data.filter = key; 
     cleanData.init(data); 
     } else { 
     window.location.hash = 'random'; 
     } 
    }; 
    request.onerror =() => { 
     console.error('Error'); 
    }; 
    request.send(); 
    }; 

    /* Check if the data is list or single, and clean up 
    --------------------------------------------------------------*/ 
    const cleanData = { 
    init(originalData) { 
     if (!originalData.results) { 
     this.single(originalData); 
     } else { 
     allData[originalData.filter] = originalData; 
     } 
    }, 

    list(data) { 
     data.results.map(function(el) { 
     el.backdrop_path = `https://image.tmdb.org/t/p/w500/${el.backdrop_path}`; 
     }); 
     let attributes = { 
     movie_image: { 
      src: function() { 
      return this.backdrop_path; 
      }, 
      alt: function() { 
      return this.title; 
      } 
     }, 
     title_url: { 
      href: function() { 
      return `#movie/${this.id}/${this.title}`; 
      } 
     } 
     } 
     showList(data.results, attributes); 
    }, 

    single(data) { 
     data.poster_path = `https://image.tmdb.org/t/p/w500/${data.poster_path}`; 
     data.budget = formatCurrency(data.budget); 
     data.revenue = formatCurrency(data.revenue); 
     data.runtime = `${(data.runtime/60).toFixed(1)} uur`; 
     data.imdb_id = `http://www.imdb.com/title/${data.imdb_id}`; 
     let attributes = { 
     movie_image: { 
      src: function() { 
      return this.poster_path; 
      }, 
      alt: function() { 
      return this.title; 
      } 
     }, 
     imdb_url: { 
      href: function() { 
      return this.imdb_id 
      } 
     }, 
     similar_url: { 
      href: function() { 
      return `#movie/${this.id}/${this.title}/similar` 
      } 
     } 
     }; 
     showSingle(data, attributes); 
    } 
    }; 

    const showList = (cleanedData, attributes) => { 
    movieList.classList.remove('hidden'); 
    movieSingle.classList.add('hidden'); 
    Transparency.render(movieList, cleanedData, attributes); 
    }; 

    const showSingle = (cleanedData, attributes) => { 
    movieSingle.classList.remove('hidden'); 
    movieList.classList.add('hidden'); 
    Transparency.render(movieSingle, cleanedData, attributes); 
    } 

const formatCurrency = amount => { 
    amount = amount.toFixed(0).replace(/./g, function(c, i, a) { 
     return i && c !== "." && ((a.length - i) % 3 === 0) ? '.' + c : c; 
    }); 
    return `€${amount},-`; 
    }; 

    app.init(); 

console.log(allData); // Returns object with 4 properties: trending, toplist, latest & upcoming. Each property is filled with 20 results (movies with data) from the API. 

console.log(allData.trending) // Returns 'undefined' (each property I've tried). 

console.log(allData['trending']) // Returns 'undefined' 

Object.keys(allData); // Returns an empty Array [] 

})(); 

当我使用console.log(allData)我看到4个属性,无不洋溢着来自API的结果。但是,当我做console.log(allData.trending)console.log(allData['trending'])它在控制台中返回'未定义'。有没有人有一个想法如何解决这个问题?

+0

是什么'Object.keys(ALLDATA)'的输出的实际快照? –

+0

@AmreshVenugopal它返回一个空数组 –

+2

看起来像属性不是对象。我的意思是,你在控制台上看到的属性来自原型。 –

回答

1

当您致电app.init()时,它会触发init并发送api调用以获取数据。

获取数据的调用是异步的,这意味着它不会等待响应继续执行。所以它继续并执行下一行代码,它们是您的console.logs。此时API调用没有对数据做出响应,因此当您尝试访问data.property时,它会失败,因为数据尚未处理。

当您执行log(data)时,它会创建一个数据引用的日志,当引用稍后填充值时,该日志将在日志中更新。要在该实例中获得data的值,并在稍后阻止更新,请尝试log(JSON.stringify(data))。当你这样做时,你会得到一个一致的结果,你的日志没有任何工作,这是实际的行为。

为了让您的日志工作,请查看A(同步)JAX请求的成功/加载回调,并从那里记录日志。或者如果您在cleanData之后构建allData,则在cleanData函数之后调用日志。

所以要回答你的问题,你的任何日志都不应该工作,因为它是一个异步调用。你得到应有记录到console.log与稍后更新引用的工作方式的allData,使用console.log(JSON.stringify(allData))获得对象

+0

非常感谢您的回答! :) –

相关问题