gpt4 book ai didi

Angular: 7.2.1 ES6 class ReferenceError : Cannot access 'X' before initialization(ANGLE:7.2.1 ES6类引用错误:初始化前无法访问‘X’)

转载 作者:bug小助手 更新时间:2023-10-24 18:10:24 35 4
gpt4 key购买 nike



I'm having the following TypeScript class

我正在上下面的打字课课



export class Vehicule extends TrackableEntity {
vehiculeId: number;
constructor() {
super();
return super.proxify(this);
}
}


my typescript target in tsconfig.json is configured as es6:

我在tsconfig.json中的输入脚本目标配置为ES6:



"compilerOptions": {
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
}


At runtime, here in Chrome, the code is failing with:

在运行时,在Chrome中,代码失败,出现以下错误:



ReferenceError: Cannot access 'Vehicule' before initialization
at Module.Vehicule (https://localhost:44338/src-app-components-dispositifsDATI-dispositifsDATI-module.js:10559:100)
at Module../src/app/domain/models/VehiculeGpsBoxInfo.ts (https://localhost:44338/src-app-components-dispositifsDATI-dispositifsDATI-module.js:11156:69)
at __webpack_require__ (https://localhost:44338/runtime.js:84:30)
at Module../src/app/domain/models/Vehicule.ts (https://localhost:44338/src-app-components-dispositifsDATI-dispositifsDATI-module.js:10571:78)
at __webpack_require__ (https://localhost:44338/runtime.js:84:30)
at Module../src/app/components/dispositifsDATI/mainDATI/listDATI/listDATI.component.ts (https://localhost:44338/src-app-components-dispositifsDATI-dispositifsDATI-module.js:6447:82)
at __webpack_require__ (https://localhost:44338/runtime.js:84:30)
at Module../src/app/components/dispositifsDATI/index.ts (https://localhost:44338/src-app-components-dispositifsDATI-dispositifsDATI-module.js:3053:95)
at __webpack_require__ (https://localhost:44338/runtime.js:84:30)
at Module../src/app/components/dispositifsDATI/dispositifsDATI.routes.ts (https://localhost:44338/src-app-components-dispositifsDATI-dispositifsDATI-module.js:2982:64)


I needed to change es5 to es6 to solve this other problem.

我需要将ES5更改为ES6来解决这个问题。






EDIT:
The VehiculeGpsBoxInfo.ts file is importing Vehicule like this:

编辑:VehiculeGpsBoxInfo.ts文件导入Vehicule时如下所示:



import { Vehicule } from "./Vehicule";


EDIT 2: I vould say that this may be webpack related, the way that modules are exported/imported in the genrated modules.

编辑2:我可以说这可能与webpack有关,在基性化的模块中导出/导入模块的方式。



EDIT 3: After further research, this seems to have nothing to do with the code shown above. Started a new question about webpack and ES6.

编辑3:经过进一步研究,这似乎与上面显示的代码没有任何关系。开始了一个关于webpack和ES6的新问题。


更多回答

Is it valid to return something in a constructor?

在构造函数中返回某些内容是否有效?

@jlang Please see this

@jlang请看这个

I had this issue and found out a service I was injecting had some injections missing providers. Check your tree

我遇到了这个问题,发现我正在注射的一个服务有一些注射缺少提供者。检查你的树

优秀答案推荐

I was getting this error due to a circular dependency, like

由于循环依赖,我收到了这个错误,比如



  • A injected with B

  • B injected with C

  • C injected with A


Removing the circular dependecy fixed this error.

删除循环依赖项已修复此错误。



You're probably running into this Angular issue: https://github.com/angular/angular-cli/issues/15077.

你可能会遇到这个角度问题:https://github.com/angular/angular-cli/issues/15077.


From that issue:

从这个问题上看:



Hi, is there a reason why you need emitDecoratorMetadata to be true?


This TypeScript option has a fundamental design limitation with ES2015+ code and is best avoided when targeting such output. As such this is an issue with TypeScript itself and not Angular.


Angular 8+ no longer requires the option. It was also previously only required for JIT mode which is typically only used in development.



The solution is to set "emitDecoratorMetadata": false in your tsconfig.json file.

解决方案是在tsconfig.json文件中设置“emitDecoratorMetadata”:FALSE。


Side note:
I must say, given that previous versions of the Angular CLI automatically added emitDecoratorMetadata: true, and there's no reason I can see why a dev should know that emitDecoratorMetadata should now be false, it's pretty horrible that the Angular team basically said "this isn't our problem" and closed the issue without action. This could have been easily "fixed" by adding some better documentation (as pointed out by someone in the linked issue).

附注:我必须说,考虑到以前版本的ANGLE CLI自动添加了emitDecoratorMetadata:True,而且我不明白为什么开发人员现在应该知道emitDecoratorMetadata应该是FALSE,这是相当可怕的,ANGLE团队基本上只说“这不是我们的问题”,并且不采取行动就结束了问题。这本来可以通过添加一些更好的文档来轻松地“修复”(正如有人在链接的问题中指出的那样)。



Note that this error can also be caused by defining two public @Injectable classes within the same .ts file.

请注意,在同一个.ts文件中定义两个公共@Injectable类也可能导致此错误。


I've tripped over this more than once when I'm just prototyping stuff locally (especially when refactoring one service into multiple).

当我只是在本地创建原型时(特别是在将一个服务重构为多个服务时),我不止一次地遇到过这一点。


Setting emitDecoratorMetadata: false does fix this situation as well; but in case you're in a hurry to fix something or don't want fiddle with thetsconfig.json file on a large project - it's useful to know that you might be able to fix it by just moving one of the classes into a new file.

设置emitDecoratorMetadata:FALSE也可以修复这种情况;但是,如果您急于修复某些东西,或者不想摆弄大型项目上的etsfig.json文件,知道您可能只需将其中一个类移动到新文件中就可以修复它,这是很有用的。



to find circular dependencies :

要查找循环依赖项,请执行以下操作:


npx madge --circular --extensions ts ./

Npx Madge--圆形--扩展ts。/


(build before)

(在此之前构建)



I ran into this due to the order of my import statements in the module. A file that also accessed the component had to be imported before the component.

由于模块中IMPORT语句的顺序,我遇到了这个问题。也访问该组件的文件必须在该组件之前导入。



I see that in 2023 there is no correct answer, but this problem is listed high enough in google.
So basically what you need to do in scenario:

我看到2023年没有正确的答案,但这个问题在谷歌上列得足够高了。因此,基本上您在场景中需要做的是:



  • A injected with B

  • B injected with C

  • C injected with A


Put all tree components in one separate module.ts e.g. abc.module.ts.
In that file you can event simpler put all components in array like this:

将所有树组件放在一个单独的模块.ts中,例如abc.mode.ts。在该文件中,您可以使用Event Simple将所有组件放入如下数组中:


export const components = [ AComponent, BComponent, CComponent, ];

导出常量组件=[AComponent,BComponent,CComponent,];


and then in @NgModule {} add this array to:
exports: [components], declarations: [components],

然后在@NgModule{}中将此数组添加到:EXPORTS:[Components],声明:[Components],


imports:[] array has all dependant components which are used by those tree. And thats it, you will be safe from ReferenceError : Cannot access 'X' before initialization

Imports:[]数组包含这些树使用的所有依赖组件。仅此而已,您将不会被引用错误:在初始化之前无法访问‘X



Circular dependency is the devil!


It causes the whole dependency loop to be unresolvable by the compiler. In most cases, the errors look like you are not importing the classes at all.

它会导致编译器无法解析整个依赖项循环。在大多数情况下,错误看起来根本没有导入类。


Some might think that circular dependencies should only be prevented in services and modules, However, circular dependency should be prevented in all forms, even in models, components, and classes.

有些人可能认为应该只在服务和模块中防止循环依赖,然而,应该在所有形式中防止循环依赖,甚至在模型、组件和类中也是如此。


When you have circular dependency it's a sign that (sooner or later) you need to refactor and restructure your code. The following hints might be useful to do so. Suppose we want to remove the circular dependency between two classes A, B.

当您有循环依赖时,这是一个迹象,表明(迟早)您需要重构和重构代码。下面的提示可能会对此有所帮助。假设我们想要删除两个类A、B之间的循环依赖。


Solution 1: Union/Merge

解决方案1:联合/合并


A and B are following the very same concept and they can be merged into a single class.

A和B遵循完全相同的概念,它们可以合并为一个类别。


Solution 2: Separation/Creation

解决方案2:分离/创建


There should be a new class C, that both A and B rely on or sits somewhere between those two.

应该有一个新的C类,A和B都依赖于或位于这两者之间的某个地方。


According to my experience, in most cases, the circular dependency happens because the developer tends to merge n logics into k (k<n) classes.

根据我的经验,在大多数情况下,循环依赖的发生是因为开发人员倾向于将n个逻辑合并成k(k



In Angular 8, having entryComponents declared as an empty list in a SharedModule caused this issue for me:

在角度8中,在SharedModule中将entryComponents声明为空列表导致了这个问题:


entryComponents: []

After removing entryComponents, everything worked fine.

删除Entry Components后,一切运行正常。



In my case, I had an index.ts file that exported components from A.ts and B.ts.

在我的例子中,我有一个从A.ts和B.ts中导出组件的index.ts文件。


B.ts tried to import from the index.ts instead of A.ts.

B.TS尝试从index.ts而不是A.ts导入。


This caused the MJS to be emitted in the incorrect order because of the cycle:

这导致MJS的发射顺序不正确,原因是循环:


B.ts -> index.ts -> B.ts

You can search for imports ending in from ".". This can be avoided by using a underscored prefix _index.ts (except in the root directory).

您可以搜索以“.”结尾的导入。这可以通过使用带下划线的前缀_index.ts来避免(根目录中除外)。


I'm posting this for others looking for other ideas that cause Cannot access 'X' before initialization. Best of luck. 👍

我张贴这篇文章是为了让其他人寻找在初始化前无法访问‘X’的其他想法。祝你好运。👍



In my case, it wasn't any circular dependency, it was a bug in an array that I export and use inside one of the components.

在我的例子中,它不是任何循环依赖,而是我导出并在其中一个组件中使用的数组中的错误。


The array is multidimensional and I used one of the indexes without initializing it first, when I opened the project I got the error:

该数组是多维的,我没有先初始化就使用了其中一个索引,当我打开项目时收到错误消息:



ReferenceError: Cannot access 'XXXModule' before initialization



I started reverting back the files one by one until I found the exact issue, but really weird how I didn't get another error explaining the wrong use of an array.

我开始一个接一个地还原文件,直到我找到确切的问题,但非常奇怪的是,我为什么没有收到解释错误使用数组的另一个错误。



For those still searching for another solution to this error, I found out that I had two equal imports in a Parent Component and Child Component and that was giving me this error 😔.

对于那些仍在寻找此错误的另一个解决方案的人,我发现我在父组件和子组件中有两个相等的导入,这给了我这个错误😔。


Example:

示例:


ParentComponent and ChildComponent both have this import:

ParentComponent和ChildComponent都具有此导入:


import { ExampleComponent } from '../example-component/example-component.component'

The solution was to remove that one line of import in one of them and the error stop

解决方案是删除其中一行中导入一行,错误停止


Hope this saves someone's time

希望这能节省某人的时间



I ran into this when I was adding another folder / entrypoint to a library. I had multiple components and was importing one into the other. The default import path VSCode used was ./public-api. Changing it to the actual component path (../folder/file) fixed the issue.

我在向库中添加另一个文件夹/入口点时遇到了这个问题。我有多个组件,正在将一个组件导入另一个组件。VSCode使用的默认导入路径是./public-api。将其更改为实际组件路径(../文件夹/文件)修复了该问题。



For people landing here from a search: When you get this error in Angular 15 or above, it might be due to circular dependencies at standalone components. In that case you can fix it with forwardRef:

对于从搜索中登录到这里的人:当您在角度15或更高时得到此错误,可能是由于独立零部件的循环依赖。在这种情况下,您可以使用forwardRef进行修复:


@Component({
standalone: true,
selector: 'app-b',
templateUrl: './b.component.html',
styleUrls: ['./b.scss'],
imports: [
forwardRef(() => AComponent))
]
})
export class BComponent implements OnInit {

}

See: https://stackoverflow.com/a/76233363/11603006

请参阅:https://stackoverflow.com/a/76233363/11603006



My issue with this was having a Service that had the wrong providedIn configuration, and I must have been providing and importing the service wrong in the actual component or somewhere else down the tree. Anyway, I only needed one instance at the root, so changing providedIn back to 'root' fixed it.

我的问题是,服务的ProvidedIn配置错误,我一定是在实际组件中或树下的其他地方错误地提供和导入了该服务。不管怎么说,我只需要一个根目录下的实例,所以把ProvidedIn改回‘根’就解决了这个问题。



that make sense, you are passing the local object (Vehicle) to the parent class within constructor return super.proxify(this);.

这是有意义的,您正在将本地对象(Vehicle)传递给构造函数返回Super.proxify(This);内的父类。



Keep in mind the local Vehicle instance has not been instantiated yet (constructor block is not finished yet), so you cannot use this object in the mean time, you need to wait the constructor to done it's job.

请记住,本地Vehicle实例尚未实例化(构造函数块尚未完成),因此您不能同时使用此对象,您需要等待构造函数完成其工作。


更多回答

This is definitely relevant and helped me figure out my issue. In my case I had a service S provided by ModuleA, used internally and by ModuleB (that didn't import ModuleA). This wasn't quite the issue, but rather that service S should've been provided by ModuleC instead.

这绝对是相关的,并帮助我解决了我的问题。在我的例子中,我有一个由模块A提供的S服务,在内部由模块B使用(不导入模块A)。这不是问题的关键,而是S应该由模块C提供的服务。

I had a circular dependency as well. Once I fixed it everything was fine again. thanks

我也有循环依赖。一旦我把它修好了,一切又都好起来了。谢谢

It was also my case, thank you !

这也是我的案子,谢谢!

You can use github.com/cexbrayat/angular-cli-diff to check a lot of stuff, included tsconfig

您可以使用githeb.com/cexbrayat/angular-cli-diff来检查很多东西,包括tsconfig

Wow you saved my life, I had the issue and it was due to a public injection within the component .ts file.

哇,你救了我的命,我有这个问题,这是由于组件.ts文件中的公共注入造成的。

Yup, guilty. Uhlala.

是的,有罪。哇啦啦。

What is madge? it a tool?

玛吉是什么?它是一种工具?

omg, this tool is indispensable, thank you!

天哪,这个工具是必不可少的,谢谢!

this saved me time and sanity so much so. Thank you so very much

这大大节省了我的时间和理智。非常感谢你

This is best!!!

这是最棒的!

This was it for me. Thanks for throwing this in the answers!

对我来说就是这样。谢谢你把这个放在答案里!

This was it for me. In my case, I did "organize imports" shortcut in VS code, and some services were imported before the AppComponent in main.ts. Making AppComponent appear first solved the problem.

对我来说就是这样。在我的例子中,我确实在VS代码中“组织导入”快捷方式,并且一些服务在main.ts中的AppComponent之前被导入。让AppComponent出现首先解决了这个问题。

This helped me though, in my case, the source of the error was in my library and I just moved the directive that caused the error to the top of its file. I bet I could have changed the export order in the public-api.ts as well. I can't believed it worked... seems flaky.

但这对我很有帮助,在我的例子中,错误的来源在我的库中,我只是将导致错误的指令移到其文件的顶部。我打赌我也可以改变公共场合的出口顺序--api.ts。我不敢相信它成功了..。看起来很不靠谱。

that's why everybody is abandoning angular

这就是为什么每个人都放弃了棱角分明

@DinaFlies Circular dependencies between modules are considered an anti-pattern because of their negative effects regardless of the platform. So it's not about angular or a specific platform.

模块之间的@DinaFlie循环依赖被认为是反模式,因为它们的负面影响与平台无关。因此,这不是角度或特定平台的问题。

I've missed the part I've mentioned circular dependencies. While angular has extra-complexity to deal with modules, other frameworks simply import their components where they are needed.

我错过了我提到的循环依赖部分。虽然Angel在处理模块方面有额外的复杂性,但其他框架只是在需要它们的地方导入它们的组件。

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

正如它目前所写的,你的答案并不清楚。请编辑以添加更多详细信息,以帮助其他人了解这是如何解决提出的问题的。你可以在帮助中心找到更多关于如何写出好答案的信息。

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com