You need to provide 1 type argument(s) for the Generic type ModuleWithProviders<T> in Angular 10 Swagger Codegen

Currently, I am generating Codegen proxies using . Upon implementing this in Angular 10, I encountered the following error. How can this issue be resolved?

The error message reads: 'Generic type 'ModuleWithProviders' requires 1 type argument(s).'

export class ApiModule {
    public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders {
        return {
            ngModule: ApiModule,
            providers: [ { provide: Configuration, useFactory: configurationFactory } ]
        };
    }

    constructor( @Optional() @SkipSelf() parentModule: ApiModule,
                 @Optional() http: HttpClient) {
        if (parentModule) {
            throw new Error('ApiModule is already loaded. Import in your base AppModule only.');
        }
        if (!http) {
            throw new Error('You need to import the HttpClientModule in your AppModule! \n' +
            'See also https://github.com/angular/angular/issues/20575');
        }
    }
}

Answer №1

This error message indicates that the ModuleWithProviders class requires one generic parameter. Therefore, it should be used as ModuleWithProviders<T>, where T represents a type.

UPDATE:

The class is outlined as follows:

interface ModuleWithProviders<T> {
  ngModule: Type<T>
  providers?: Provider[]
}

.

export class ApiModule {
  public static forRoot(configurationFactory: () => Configuration) : ModuleWithProviders<ApiModule> {
    return {
        ngModule: ApiModule,
        providers: [ { provide: Configuration, useFactory: configurationFactory } ]
    };
}

Explore Resource:

https://angular.io/guide/migration-module-with-providers

Answer №2

io.swagger.swagger-codegen officially added full support for Angular 10 starting from version 2.4.17. For more information on the specific fix included in this update, you can refer to this pull request.

In line with the recommendation from djf, make sure to utilize the parameter

--additional-properties ngVersion=10
when executing the generate command to instruct io.swagger.swagger-codegen to integrate Angular 10.

Answer №3

We encountered a similar issue but found a solution. By using custom *.mustache templates with the swagger-codegen-cli and the -t switch (refer to the swagger doc), you can customize the behavior.

Our modified api.module.mustache template now appears as follows:

import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core';
import { Configuration } from './configuration';
{{#useHttpClient}}import { HttpClient } from '@angular/common/http';{{/useHttpClient}}
{{^useHttpClient}}import { Http } from '@angular/http';{{/useHttpClient}}

{{#apiInfo}}
{{#apis}}
import { {{classname}} } from './{{importPath}}';
{{/apis}}
{{/apiInfo}}

@NgModule({
  imports:      [],
  declarations: [],
  exports:      [],
  providers: [
    {{#apiInfo}}{{#apis}}{{classname}}{{#hasMore}},
    {{/hasMore}}{{/apis}}{{/apiInfo}} ]
})
export class ApiModule {
    public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders<ApiModule> {
        return {
            ngModule: ApiModule,
            providers: [ { provide: Configuration, useFactory: configurationFactory } ]
        };
    }

    constructor( @Optional() @SkipSelf() parentModule: ApiModule,
                 @Optional() http: {{#useHttpClient}}HttpClient{{/useHttpClient}}{{^useHttpClient}}Http{{/useHttpClient}}) {
        if (parentModule) {
            throw new Error('ApiModule is already loaded. Import in your base AppModule only.');
        }
        if (!http) {
            throw new Error('You need to import the {{#useHttpClient}}HttpClientModule{{/useHttpClient}}{{^useHttpClient}}HttpModule{{/useHttpClient}} in your AppModule! \n' +
            'See also https://github.com/angular/angular/issues/20575');
        }
    }
}

The only modification needed is changing ModuleWithProviders to

ModuleWithProviders<ApiModule>
. This adjustment ensures compatibility with Angular 10 when generating api.module.ts files.

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

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

Holding an element in TypeScript Angular2 proved to be challenging due to an error encountered during the process

I attempted to access a div element in my HTML using ElementRef, document, and $('#ID') but unfortunately, it did not work. I tried implementing this in ngOnInit, ngAfterViewInit, and even in my constructor. Another method I tried was using @Vie ...

Utilizing Angular's ngIf directive to output the result of a condition

In my project, there is a unique card-list element that has the capability to display either elements from the card component or the card-edit component based on the value of the wasEditClicked property in the card component. The structure of the card-lis ...

Angular 4 - The Promising Outcome: How to Retrieve the Value upon Completion

Is there a way to retrieve a value from a promise and store it in a global variable? I've been attempting to accomplish this, but the global variable remains undefined. import { Injectable } from '@angular/core'; import {ActivatedRouteSnap ...

Using Typescript: Undefined arrays could cause issues in the array map function

Encountering a Typescript error stating that '<array name>' is possibly undefined while attempting to map over an array in Typescript. Below is an example code snippet triggering this issue: type obj = { list?: string[] }; function dem ...

Guide to creating a tailored regex validator for reactive forms in Angular 6

I'm currently working with Angular 6 and attempting to validate an email using a regular expression pattern, but I'm encountering an issue. When I try to use the code for validation, I receive the following error message: ReactiveFormComponent ...

Two separate menus for each root file in Ionic 2

In my Ionic 2 project, I have developed two root files: app.component and report-menu. In order to make the report-menu module accessible in the app.component.module.ts file, I imported it successfully. However, I am facing an issue where one menu is dis ...

Obtain a union type using the `keyof typeof` syntax

Is there a way to retrieve the union or enum type from a typeof type in TypeScript? For instance: const myConfs: { [k: string]: (myArg: { name: string }) => string } = { 'Hello': ({ name }) => `World from ${name}`, 'Goodbye': ...

Find the dominant color within the project's style sheets

Is there a method to extract the main color from an angular material theme and apply it in the css files of an angular project? Within a project, we can specify the primary color in a *.scss document as shown below: @import '~@angular/material/themi ...

What is the best way to synchronize API definitions between the server and client using TypeScript?

My setup involves a server (TypeScript, NestJS) and a client (TypeScript, Angular) that communicate with each other. Right now, I have the API response DTO classes defined in both the server to output data and in the client to decode the responses into a ...

How can one effectively import and save data from a CSV file into an array comprised of objects?

I am looking to read a CSV file and store it in a variable for future access, preferably as an array of objects. However, when trying the following code snippet: const csv = fs .createReadStream('data.csv') .pipe(csv.default({ separator: &ap ...

Angular 2 - Component remains active upon page transition

I am currently working on a large Angular2 application. I have set up two routes - /rewards which displays a list of all rewards and /reward/{rewardName} which shows detailed information about a specific reward. However, I am facing an issue where each tim ...

Learn how to showcase vertical text in React Native similar to a drawer

Looking for a way to display text vertically in a dynamic manner, where the length of the text can vary. Below are some examples for reference: Example 1 Example 2 <View> <View style={{}}> <View style={{ marginTop: 30, flexDire ...

Ways to cite a vendor in static class functions?

Is there a method to access a service provided at bootstrap within static class methods? I don't have any code to share right now, but I've been experimenting with the standard syntax using Injector (you can find more information here). Whenever ...

"Displaying the Material Input TextBox in a striking red color when an error occurs during

After referring to the links provided below, I successfully changed the color of a textbox to a darkish grey. Link 1 Link 2 ::ng-deep .mat-form-field-appearance-outline .mat-form-field-outline { color: #757575!important; } Although this solved the ...

MAJOR UPDATE: webpack versions before 5 previously contained polyfills for node.js specifically for 'timers-browserify'

Hey there, I'm encountering the error message below: ./node_modules/xml2js/lib/parser.js:38:17-47 - Error: Module not found: Error: Can't resolve 'timers' in '/Users/differentname/Desktop/workfiles/webdoc/ngx-admin-1/node_modules/x ...

Sorry, I am not able to perform this task as it involves paraphrasing code snippets which can lead to functional changes and potential errors in the code. I recommend seeking assistance from a developer or programmer to

I encountered an issue while trying to convert an HTML file to a PDF file in my project. Can anyone provide guidance on how to resolve this problem? npm install jspdf DownloadCvCompanent.ts: import { Component, ElementRef, OnInit, ViewChild } from '@ ...

What could be causing the issue of my application not being able to operate on the specified port on Heroku?

After spending two whole days trying to decipher the Heroku error message with no success, I'm still unable to pinpoint what is causing the issue. 2021-07-18T04:27:08.741998+00:00 app[web.1]: {"level":30,"time":1626582428741,&quo ...

Is it possible that a declaration file for module 'material-ui/styles/MuiThemeProvider' is missing?

I have been trying to implement the react material-ui theme after installing it via npm. However, I am encountering errors when adding 'import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";' in boot-client.tsx: TS7016: Could not ...

What is the best way to retrieve a value from async/await functions?

async function fetchNetworkStatus() { const network = await Network.getConnection(); setConnection(network.isConnected); console.log(connectionStatus); if (network.isConnected) { return true; } else { ...