Using Angular's dependency injection in a project that has been transpiled with Babel

I am currently attempting to transpile my Angular 6 project, which is written in TypeScript, using the new Babel 7. However, I am facing challenges with getting dependency injection to function properly.

Every time I try to launch the project in Chrome, I encounter the following error:

Uncaught Error: Can't resolve all parameters for AppComponent: (?).
at syntaxError (compiler.js:1270)
at CompileMetadataResolver._getDependenciesMetadata (compiler.js:11171)
at CompileMetadataResolver._getTypeMetadata (compiler.js:11064)
at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (compiler.js:10683)
at CompileMetadataResolver._getEntryComponentMetadata (compiler.js:11267)
at eval (compiler.js:10927)
at Array.map (<anonymous>)
at CompileMetadataResolver.getNgModuleMetadata (compiler.js:10927)
at JitCompiler._loadModules (compiler.js:24104)
at JitCompiler._compileModuleAndComponents (compiler.js:24085)

To demonstrate the issue, I have created a fork of a boilerplate and added a simple httpClient service injection: https://github.com/gnihi/angular-6-with-babel-typescript

If I remove the constructor from app.component.ts, everything functions as expected.

Below are the dependencies of the project:

{
"devDependencies": {
    "@babel/core": "^7.1.2",
    "@babel/plugin-proposal-class-properties": "^7.1.0",
    "@babel/plugin-proposal-decorators": "^7.1.2",
    "@babel/preset-env": "^7.1.0",
    "@babel/preset-typescript": "^7.1.0",
    "babel-loader": "^8.0.0",
    "babel-plugin-transform-decorators": "^6.24.1",
    "webpack": "^4.17.1",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.7"
},
"scripts": {
    "build:dev": "webpack --mode development",
    "build:prod": "webpack --mode production",
    "dev": "webpack-dev-server --mode development --content-base=./dist/",
    "type-check": "tsc"
},
"dependencies": {
    "@angular/common": "^6.1.6",
    "@angular/compiler": "^6.1.6",
    "@angular/core": "^6.1.6",
    "@angular/platform-browser-dynamic": "^6.1.6",
    "@angular/platform-browser": "^6.1.6",
    "core-js": "^2.5.7",
    "zone.js": "^0.8.26"
}
}

Your assistance and guidance are greatly appreciated. Thank you!

Answer №1

After reaching out to the creator of the original repository, I received a response regarding my inquiry (https://github.com/hzub/angular-6-with-babel-typescript/issues/2#event-1919783976). The issue seems to lie in the application's inability to resolve dependencies. The suggestion was made to transition to explicit dependency injection (angular.core.Inject). For more information, check out this link: .

Answer №2

During my migration from AngularJs to Angular, I encountered a similar issue related to decorators that the compiler was struggling to interpret.

To resolve this issue, I found success by making adjustments in both my package.json and webpack configuration:

 "reflect-metadata": "^0.1.10",
"babel-plugin-transform-typescript-metadata": "^0.3.2"

It's important to note that "babel-plugin-transform-typescript-metadata" should be placed before proposal decorators plugin in your plugins array within the webpack config.

plugins: [....
            "babel-plugin-transform-typescript-metadata",
            ['@babel/plugin-proposal-decorators', { legacy: true }],
          ],

Additionally, don't forget to import the reflect metadata in the main.ts file.

import 'reflect-metadata';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: TypeScript compilation failed due to absence of tsc command in the system

Hello, I recently installed TypeScript and encountered an issue when trying to initialize tsc -v in the terminal. The error message I received was "bash: tsc: command not found." During the installation process, I used npm install -g typescript@latest whi ...

Angular CLI fails to generate angular-cli.json file

Currently in the process of creating a new PWA and I need to input information into angular-cli.json. Utilizing Angular CLI: 1.7.4 Node: 8.11.1 OS: win32 x64 Angular: 5.2.10. Upon running ng new pwaapp --service-worker, the project folder does not conta ...

Angular 2: Finding the object with the highest attribute value in an array of objects

I am currently developing an Angular 2 application and I have an array of objects. My goal is to return the object that has the maximum value of a specific attribute (in this case, the object with the most likes). How can I achieve this in TypeScript? i ...

Errors in TypeScript are being brought up by using if-else statements inside a loop

I am currently working on a function to retrieve referral codes from users. The user inputs a code, which is then checked against the database to see if it exists or not If the code provided matches the current user's code, it should not be accept ...

Steps for personalizing the dataset on a PrimeNG bar graph

I'm currently working with primeng in an Angular project and I need to create a bar chart where the last two horizontal bars have different colors. Right now, the last two bars are incorrectly being assigned to represent dogs and cats. My goal is to ...

Optimal approach for designing interfaces

I have a situation where I have an object retrieved from the database, which includes assignee and author ID properties that refer to user objects. As I transform a number into a user object, I am unsure about the best practice for defining the type of the ...

Looping through the json resulted in receiving a null value

When working with typescript/javascript, I encountered an issue while trying to fetch the 'statute' from a data object: {_id: "31ad2", x: 21.29, y: -157.81, law: "290-11",....} I attempted to assign data.law to a variable, but received a typeer ...

Angular: Activate async validator for form group only when all controls have values

Is there a way to trigger validation for FormGroup only after all the fields in the group have been filled out, instead of triggering it every time a field is filled? ...

Verify if an object property is called with the toHaveBeenCalledWith() function in Jasmine

Recently started incorporating Jasmine into my workflow and I am trying to verify if my method was called with an object that includes a MyProperty property. Currently, my setup looks like this: expect(service['method']).toHaveBeenCalledWith(jasm ...

Explaining the process of defining an object type in TypeScript and the conversion from JavaScript

Currently, I am attempting to enhance the background of a React website developed in typescript (.tsx) by incorporating particles. My approach involves utilizing the particle-bg component available at: https://github.com/lindelof/particles-bg However, whe ...

Determining the quantity of variations within a union in Typescript

Is it possible to determine the number of types in a union type in Typescript, prior to runtime? Consider the following scenario: type unionOfThree = 'a' | 'b' | 'c'; const numberOfTypes = NumberOfTypes<unionOfThree>; c ...

The AOT Compilation error occurs in Angular2 RC6 when trying to call the function RouterModule.forChild(ROUTES) which is not supported

Operating Environment: Windows 10, IntelliJ 2016.2, node Angular Version: 2.0.0-rc.6 Language: [all | TypeScript X.X | ES6/7 | ES5] Typescript ES6 Node (for Ahead of Time Compilation issues): node --version = Node 4.4.7, NPM 3.10.6 The AOT com ...

Transform a Typescript type that includes multiple string options into an array containing those options as values

Sending Status: const statusArray = ["confirmed", "pending", "canceled"] Purpose: While the type is automatically generated, I also require it to be in array form. ...

Execute environment validation on server during `next build` command

I have a src/config/server/ts file that contains the following code: 'use server'; import zod from 'zod'; if (typeof window !== 'undefined') { throw new Error('env should not be imported on the frontend!'); } co ...

Having trouble accessing the theme in a styled component with @emotion/styled

https://i.stack.imgur.com/zHLON.png I've been using @emotion/react for theming and successfully injected the theme into it. I can access the theme using useTheme within components, but I'm facing some difficulties in accessing the theme within s ...

Resetting md-radio-button choices within an Angular 2 application

My Angular app has a sorting filter using radio buttons via md-radio-group for users to choose how they want data displayed. The radio buttons work fine, but I'm struggling to clear them when the "Restore Defaults" button is clicked. This is the code ...

Utilizing Angular 16 to Link Component Input with Parent Route Parameter

Picture a scenario where there is a component (some.component.ts) in Angular 16 that retrieves the value for its foo property from activeRoute, specifically from the parent route. Take a look at the code snippet below: @Input() foo!: string; constructor(p ...

The fixed header option is not available for the CdkVirtualScrollViewport

Looking for a solution in my Angular application where I need to keep the table header at a fixed position while displaying the scrollbar only on the body part. Currently, I am utilizing the CdkVirtualScrollViewport library in Angular to render the table c ...

connect the validation of forms to different components

I am currently working on components to facilitate the user addition process. Below is an example of my form component: createForm(): void { this.courseAddForm = this.formBuilder.group({ name: ['', [ Validators.required, ...

Converting an image file from the local directory to base64 encoding in an Angular application

Can someone help me convert a locally stored image named xyz.JPEG from the folder assets/img to base64 in Angular 8? I have attempted using FileReader and btoa, but it has not been successful. var reader = new FileReader(); var binaryString = reader.rea ...