简体   繁体   中英

(Angular/Typescript) can't use variable to access JSON object

I am very confused at the moment. What I am trying to accomplish is very simple. I need to be able to use a variable to access a specific JSON object. I have created a service which imports a JSON file. the app component then uses this service and calls a function printData which takes in the JSON object key of what you want to acesss. The oddest part of this problem is that it works fine on stackblitz!

[Click to see stackblitz] https://stackblitz.com/edit/angular-json-related-project

I have tried the exact same code as above on two local machines and I get the same error!

core.js:4081 ERROR TypeError: Cannot read property 'name' of undefined
    at DataServiceService.printData (data-service.service.ts:10)
    at new AppComponent (app.component.ts:13)
    at NodeInjectorFactory.AppComponent_Factory [as factory] (app.component.ts:14)
    at getNodeInjectable (core.js:3913)
    at instantiateRootComponent (core.js:7837)
    at createRootComponent (core.js:18351)
    at ComponentFactory$1.create (core.js:22287)
    at ApplicationRef.bootstrap (core.js:28020)
    at core.js:27731
    at Array.forEach (<anonymous>)

Another thing I find odd is that this will work

printData() {
    console.log(data['movies'].name);
}

but this won't

printData() {
    var objectName = 'movies';
    console.log(data[objectName].name);
}

I have already added "resolveJsonModule": true and "esModuleInterop": true in the project locally. If anyone can help me I would very much appreciate it.

printData() {
  var objectName = 'movies';
  console.log(data.default[objectName].name); //or data['default'][objectName].name
}

Modules are special type of objects, if you console out the imported module you will see the actual values are contained inside the default key.

console.log(data)

output = Module {default: {…}, __esModule: true, Symbol(Symbol.toStringTag): "Module"}

You don't, however, need to use the default key if you access the values directly with a string:

printData() {
  console.log(data['movies'].name);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM