简体   繁体   English

(Angular/Typescript) 不能使用变量来访问 JSON object

[英](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.我需要能够使用变量来访问特定的 JSON object。 I have created a service which imports a JSON file.我创建了一个导入 JSON 文件的服务。 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.然后,应用程序组件使用此服务并调用 function printData,它接收您想要访问的 JSON object 密钥。 The oddest part of this problem is that it works fine on stackblitz!这个问题最奇怪的部分是它在 stackblitz 上运行良好!

[Click to see stackblitz] https://stackblitz.com/edit/angular-json-related-project [点击查看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.我已经在本地项目中添加了 "resolveJsonModule": true 和 "esModuleInterop": true 。 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.模块是一种特殊类型的对象,如果你控制导入的模块,你会看到实际值包含在default键中。

console.log(data)

output = Module {default: {…}, __esModule: true, Symbol(Symbol.toStringTag): "Module"} 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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