### Install ng-openapi and HTTP Resource Plugin Source: https://ng-openapi.dev/guide/http-resource Install the plugin alongside ng-openapi using npm. ```bash npm install ng-openapi @ng-openapi/http-resource --save-dev ``` -------------------------------- ### Install and Generate OpenAPI Client Source: https://ng-openapi.dev/ Install the ng-openapi package as a dev dependency and then use the CLI to generate API clients from your OpenAPI specification file. ```bash npm install ng-openapi --save-dev ng-openapi -i swagger.json -o ./src/api ``` -------------------------------- ### Install ng-openapi with pnpm Source: https://ng-openapi.dev/getting-started/installation Install ng-openapi as a development dependency using pnpm. ```bash pnpm add ng-openapi --save-dev ``` -------------------------------- ### Install ng-openapi with npm Source: https://ng-openapi.dev/getting-started/installation Install ng-openapi as a development dependency using npm. ```bash npm install ng-openapi --save-dev ``` -------------------------------- ### Globally Install ng-openapi Source: https://ng-openapi.dev/getting-started/installation Install ng-openapi globally using npm. ```bash npm install -g ng-openapi ``` -------------------------------- ### Install ng-openapi with yarn Source: https://ng-openapi.dev/getting-started/installation Install ng-openapi as a development dependency using yarn. ```bash yarn add ng-openapi --dev ``` -------------------------------- ### Verify ng-openapi Installation Source: https://ng-openapi.dev/getting-started/installation Verify the installation of ng-openapi by checking its version. ```bash ng-openapi --version ``` -------------------------------- ### Directory Organization for Clients Source: https://ng-openapi.dev/guide/multiple-clients Keep clients in separate directories to maintain a clean project structure. This example shows how configuration files map to output directories. ```bash ng-openapi -c users-api.config.ts # outputs to ./src/api/users ng-openapi -c orders-api.config.ts # outputs to ./src/api/orders ``` -------------------------------- ### Display 'generate' Subcommand Help Source: https://ng-openapi.dev/guide/cli-usage Get detailed help for the 'generate' subcommand, including its specific options and usage. ```bash ng-openapi generate --help ``` -------------------------------- ### ng-openapi Configuration File Example Source: https://ng-openapi.dev/guide/cli-usage Define detailed generation options, including input/output paths, date types, enum styles, custom headers, and response type mappings, within a configuration file. ```typescript import { GeneratorConfig } from "ng-openapi"; const config: GeneratorConfig = { input: "./swagger.json", output: "./src/api", options: { dateType: "Date", enumStyle: "enum", customHeaders: { "X-API-Key": "key" }, responseTypeMapping: { "application/pdf": "blob" }, }, }; export default config; ``` -------------------------------- ### NPM Script for Client Generation Source: https://ng-openapi.dev/guide/cli-usage Integrate API client generation into your npm scripts for seamless development workflows. This example shows generating the client before serving the application. ```json { "scripts": { "generate:client": "ng-openapi -c openapi.config.ts", "dev": "npm run generate:client && ng serve", "prebuild": "npm run generate:client", "build": "ng build" } } ``` -------------------------------- ### Manual Setup of DateInterceptor Source: https://ng-openapi.dev/guide/date-handling Register `DateInterceptor` using `HTTP_INTERCEPTORS` in the application's providers for manual control over date transformation. ```typescript import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from "@angular/common/http"; import { DateInterceptor } from "./client/utils/date-transformer"; export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(withInterceptorsFromDi()), { provide: HTTP_INTERCEPTORS, useClass: DateInterceptor, multi: true }, ], }; ``` -------------------------------- ### Manual Setup of DateInterceptor in Angular Source: https://ng-openapi.dev/api/utilities/date-transformer Register the DateInterceptor using the HTTP_INTERCEPTORS multi-provider in your app.config.ts for manual configuration. ```typescript import { ApplicationConfig } from "@angular/core"; import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from "@angular/common/http"; import { DateInterceptor } from "./client/utils/date-transformer"; import { BASE_PATH } from "./client/tokens"; export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(withInterceptorsFromDi()), { provide: HTTP_INTERCEPTORS, useClass: DateInterceptor, multi: true }, { provide: BASE_PATH, useValue: "https://api.example.com" }, ], }; ``` -------------------------------- ### Plugin-specific Output Directories Source: https://ng-openapi.dev/guide/generated-code Examples of additional directories generated by plugins, such as the Zod plugin for schemas and the HTTP Resource plugin for services. ```tree validators/ └── *.ts # Zod schemas, one file per controller ``` ```tree resources/ └── *.ts # httpResource-based services ``` -------------------------------- ### Date Transformer Example Source: https://ng-openapi.dev/api/utilities This example shows how the Date Transformer utility automatically converts ISO date strings in API responses to JavaScript Date objects. ```typescript // Automatically transforms ISO date strings to Date objects { "createdAt": "2024-01-15T10:30:00Z" } // becomes { "createdAt": Date } ``` -------------------------------- ### Provide Default Client with Base Path Source: https://ng-openapi.dev/api/providers Configure the default OpenAPI client with a base path for API requests. This is a common setup for Angular applications. ```typescript import { provideDefaultClient } from "./api/providers"; // generated file in your output directory import { provideHttpClient } from "@angular/common/http"; import { ApplicationConfig } from "@angular/core"; export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(), provideDefaultClient({ basePath: "https://api.example.com", }), ], }; ``` -------------------------------- ### Customizing Date Regex for Manual Setups Source: https://ng-openapi.dev/api/utilities/date-transformer Instantiate DateInterceptor or call transformDates directly with a custom regex for manual configurations. ```typescript new DateInterceptor(/your-custom-pattern/); transformDates(responseBody, /your-custom-pattern/); ``` -------------------------------- ### Configure HttpResourcePlugin in ng-openapi Source: https://ng-openapi.dev/api/configuration/plugins Example of how to configure the HttpResourcePlugin in your `openapi.config.ts` file. Ensure the `plugins` property is at the top level of your configuration object. ```typescript import { GeneratorConfig } from 'ng-openapi'; import { HttpResourcePlugin } from '@ng-openapi/http-resource'; export default { plugins: [HttpResourcePlugin], ... // other configurations } as GeneratorConfig; ``` -------------------------------- ### Configure ng-openapi Generation Options Source: https://ng-openapi.dev/api/configuration/options Example of how to configure generation options in an `openapi.config.ts` file. This includes settings for date types, enum styles, service generation, custom headers, and response type mappings. ```typescript import { GeneratorConfig } from 'ng-openapi'; const config: GeneratorConfig = { options: { dateType: 'Date', enumStyle: 'enum', generateServices: true, generateEnumBasedOnDescription: false, customHeaders: { 'Accept': 'application/json', ... // other headers }, responseTypeMapping: { 'application/pdf': 'blob', ... // other mappings }, ... // other configurations } }; export default config; ``` -------------------------------- ### Provide Default API Client in Angular Source: https://ng-openapi.dev/ Configure your Angular application to use the generated API client by providing the default client with its base path. This setup is typically done in your application's configuration file. ```typescript // Use in your Angular app import { provideDefaultClient } from './api/providers'; export const appConfig: ApplicationConfig = { providers: [ provideDefaultClient({ basePath: 'https://api.example.com' }) ] }; ``` -------------------------------- ### Configure Response Type Mapping Source: https://ng-openapi.dev/api/configuration/options/response-type-mapping Configure the `responseTypeMapping` option in your `openapi.config.ts` file to specify how different MIME types should be handled. This example maps PDF to 'blob', JSON to 'json', and plain text to 'text'. ```typescript // openapi.config.ts import { GeneratorConfig } from 'ng-openapi'; const config: GeneratorConfig = { options: { responseTypeMapping: { 'application/pdf': 'blob', 'application/json': 'json', 'text/plain': 'text', // Add more mappings as needed }, }, ... // other configurations }; export default config; ``` -------------------------------- ### Use Generated API Services in Angular Component Source: https://ng-openapi.dev/getting-started/quick-start Inject and use the generated services within your Angular components to interact with the API. This example demonstrates fetching a list of pets and displaying them as a signal. ```typescript import { inject } from "@angular/core"; import { toSignal } from "@angular/core/rxjs-interop"; import { PetsService } from "./api/services"; import { Pet } from "./api/models"; export class PetsComponent { private readonly petsService = inject(PetsService); readonly pets = toSignal(this.petsService.listPets()); } ``` -------------------------------- ### Customize Method Name Function Source: https://ng-openapi.dev/api/configuration/options/customize-method-name Define a custom function to derive method names from operationIds. This example splits the operationId by underscore and takes the last part, then converts it to camelCase. ```typescript import { GeneratorConfig } from 'ng-openapi'; const config: GeneratorConfig = { options: { customizeMethodName: (operationId: string) => { const methodName = operationId.split('_').pop() ?? operationId; return methodName.charAt(0).toLowerCase() + methodName.slice(1); } }, ... // other configurations }; export default config; ``` -------------------------------- ### OpenAPI Enum with JSON Description Source: https://ng-openapi.dev/api/configuration/options/generate-enums-description Example of an OpenAPI enum definition where the description field contains a JSON string representing an array of `EnumValueObject`. This format is used to derive descriptive enum names. ```json { "Status": { "enum": [0, 1], "type": "integer", "description": "[{\"Name\":\"Active\",\"Value\":0},{\"Name\":\"InActive\",\"Value\":1}]", "format": "int32" } } ``` -------------------------------- ### Generation using Configuration File Source: https://ng-openapi.dev/api/cli Utilize a configuration file to manage generation settings. This is useful for complex or repeatable configurations. ```bash ng-openapi -c openapi.config.ts ``` -------------------------------- ### Generate API Client via CLI Source: https://ng-openapi.dev/getting-started/quick-start Use the command line interface to generate the API client. Specify the input OpenAPI file and the output directory. ```bash ng-openapi -i ./swagger.json -o ./src/api ``` -------------------------------- ### Generate API Client using 'generate' Subcommand Source: https://ng-openapi.dev/guide/cli-usage Use the 'generate' subcommand for explicit API client generation. A short alias 'gen' is also available. ```bash ng-openapi generate -i swagger.json -o ./src/api ``` ```bash ng-openapi gen -c openapi.config.ts ``` -------------------------------- ### Generate API Client via Configuration File Source: https://ng-openapi.dev/getting-started/quick-start Create a TypeScript configuration file to define generation settings. This allows for more complex configurations and options. ```typescript import { GeneratorConfig } from "ng-openapi"; const config: GeneratorConfig = { input: "./swagger.json", output: "./src/api", options: { dateType: "Date", enumStyle: "enum", }, }; export default config; ``` ```bash ng-openapi -c openapi.config.ts ``` -------------------------------- ### Manual Client Configuration with Base Path Token Source: https://ng-openapi.dev/api/providers Manually configure the OpenAPI client by providing the base path token. This offers fine-grained control for complex scenarios. ```typescript import { provideHttpClient } from "@angular/common/http"; import { ApplicationConfig } from "@angular/core"; import { BASE_PATH } from "./api/tokens"; export const appConfig: ApplicationConfig = { providers: [provideHttpClient(), { provide: BASE_PATH, useValue: "https://api.example.com" }], }; ``` -------------------------------- ### Configure API Client Providers Source: https://ng-openapi.dev/guide/multiple-clients Set up the application providers to include the generated API clients, specifying their base paths for communication. ```typescript // app.config.ts import { ApplicationConfig } from "@angular/core"; import { provideHttpClient } from "@angular/common/http"; import { provideUsersClient } from "./api/users/providers"; import { provideOrdersClient } from "./api/orders/providers"; export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(), provideUsersClient({ basePath: "https://users-api.example.com", }), provideOrdersClient({ basePath: "https://orders-api.example.com", }), ], }; ``` -------------------------------- ### Generate API Clients Source: https://ng-openapi.dev/guide/multiple-clients Use the ng-openapi CLI command to generate API clients based on their respective configuration files. ```bash ng-openapi -c users-api.config.ts ng-openapi -c orders-api.config.ts ``` -------------------------------- ### NPM Script to Fetch Spec and Generate Client Source: https://ng-openapi.dev/guide/cli-usage Combine fetching the OpenAPI specification using `curl` with client generation in a single npm script. This automates the process of updating the spec and regenerating the client. ```json { "scripts": { "fetch:spec": "curl https://api.example.com/swagger.json > swagger.json", "generate:client": "npm run fetch:spec && ng-openapi -c openapi.config.ts" } } ``` -------------------------------- ### Display ng-openapi Help Information Source: https://ng-openapi.dev/guide/cli-usage View the general help message for the ng-openapi CLI, which lists all available commands and global options. ```bash ng-openapi --help ``` -------------------------------- ### NPM Scripts for Multiple API Clients Source: https://ng-openapi.dev/guide/cli-usage Manage generation for multiple distinct APIs by defining separate configuration files and npm scripts for each. A master script can then trigger generation for all APIs. ```json { "scripts": { "generate:users": "ng-openapi -c users-api.config.ts", "generate:orders": "ng-openapi -c orders-api.config.ts", "generate:all": "npm run generate:users && npm run generate:orders" } } ``` -------------------------------- ### Generate API Client from URL Source: https://ng-openapi.dev/guide/cli-usage Generate API clients directly from an OpenAPI specification hosted at a URL. This is useful for fetching the spec from a remote service. ```bash ng-openapi -i https://api.example.com/openapi.yaml -o ./src/api ``` -------------------------------- ### Output Structure with generateServices: false Source: https://ng-openapi.dev/guide/generated-code Shows the reduced output directory structure when `generateServices` is set to false. ```tree / ├── models/ │ ├── index.ts │ └── request-params.ts └── index.ts ``` -------------------------------- ### Configure ng-openapi Client Providers Source: https://ng-openapi.dev/guide/angular-integration Set up the ng-openapi client by providing the necessary configuration, including the base API path, in your Angular application's configuration. ```typescript import { ApplicationConfig } from "@angular/core"; import { provideHttpClient } from "@angular/common/http"; import { provideDefaultClient } from "./client/providers"; export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(), provideDefaultClient({ basePath: "https://api.example.com", }), ], }; ``` -------------------------------- ### Configure Users API Client Source: https://ng-openapi.dev/guide/multiple-clients Define the configuration for generating the Users API client, specifying input and output paths, and generation options. ```typescript import { GeneratorConfig } from "ng-openapi"; const config: GeneratorConfig = { clientName: "Users", input: "./users-swagger.json", output: "./src/api/users", options: { dateType: "Date", enumStyle: "enum", }, }; export default config; ``` -------------------------------- ### Environment Configuration for Multiple Clients Source: https://ng-openapi.dev/guide/multiple-clients Configure multiple clients using environment-specific base paths. This ensures each client connects to the correct API endpoint based on the environment. ```typescript import { environment } from "../environments/environment"; export const appConfig: ApplicationConfig = { providers: [ provideUsersClient({ basePath: environment.usersApiUrl, }), provideOrdersClient({ basePath: environment.ordersApiUrl, }), ], }; ``` -------------------------------- ### Configure Output Directory Source: https://ng-openapi.dev/api/configuration/output Set the `output` property in your `openapi.config.ts` file to define the destination for generated files. The directory will be created if it doesn't exist. ```typescript import { GeneratorConfig } from 'ng-openapi'; const config: GeneratorConfig = { input: './swagger.json', output: './src/client', ... // other configurations }; export default config; ``` -------------------------------- ### Basic CLI Usage Source: https://ng-openapi.dev/api/cli The fundamental structure for invoking the ng-openapi CLI. Replace `[command]` with a specific action and `[options]` with desired flags. ```bash ng-openapi [command] [options] ``` -------------------------------- ### Provide Client with Interceptors Source: https://ng-openapi.dev/api/providers Configure the default OpenAPI client with client-specific interceptors. Pass the interceptor classes, not instances, as the provider will instantiate them. ```typescript provideDefaultClient({ basePath: "https://api.example.com", interceptors: [AuthInterceptor, LoggingInterceptor], // classes, not instances }); ``` -------------------------------- ### File Download Operator Usage Source: https://ng-openapi.dev/api/utilities Demonstrates how to use the File Download Helper RxJS operator to handle file downloads initiated by an Angular service. ```typescript this.reportService.getReportById(123).pipe(downloadFileOperator("report.pdf")).subscribe(); ``` -------------------------------- ### Define Configuration with defineConfig Source: https://ng-openapi.dev/api/configuration Use the `defineConfig` helper for full autocomplete and inline type errors when configuring the generator. This is the recommended approach. ```typescript // openapi.config.ts import { defineConfig } from "ng-openapi"; export default defineConfig({ input: "./swagger.json", output: "./src/api", options: { dateType: "Date", enumStyle: "enum", }, }); ``` -------------------------------- ### Implement IPluginGenerator Interface Source: https://ng-openapi.dev/guide/plugin-authoring A plugin is a class that implements the IPluginGenerator interface. It is constructed with a PluginGeneratorContext and must implement the generate method to emit files. ```typescript import { IPluginGenerator, PluginGeneratorContext } from "ng-openapi"; import * as path from "path"; export class MyPlugin implements IPluginGenerator { private readonly context: PluginGeneratorContext; constructor(context: PluginGeneratorContext) { this.context = context; } async generate(outputRoot: string): Promise { const { spec, project, onWarning } = this.context; if (spec.operations.length === 0) { onWarning?.("Nothing to generate: the specification has no operations"); return; } const file = project.createSourceFile(path.join(outputRoot, "my-plugin", "index.ts"), "", { overwrite: true, }); // ... build the file from spec.operations / spec.definitions ... file.formatText(); file.saveSync(); } } ``` -------------------------------- ### Direct Generation from Spec Source: https://ng-openapi.dev/api/cli Generate API code directly from a local OpenAPI specification file. Specify the input file and the desired output directory. ```bash ng-openapi -i swagger.json -o ./src/api ``` -------------------------------- ### downloadFile Function Source: https://ng-openapi.dev/api/utilities/file-download-helper This function directly handles the download of a Blob to the client. It creates a temporary URL, an anchor element, triggers the download, and cleans up resources. ```typescript import { Observable } from "rxjs"; import { tap } from "rxjs/operators"; export function downloadFile(blob: Blob, filename: string, mimeType?: string): void { // Create a temporary URL for the blob const url = window.URL.createObjectURL(blob); // Create a temporary anchor element and trigger download const link = document.createElement("a"); link.href = url; link.download = filename; // Append to body, click, and remove document.body.appendChild(link); link.click(); document.body.removeChild(link); // Clean up the URL window.URL.revokeObjectURL(url); } ``` -------------------------------- ### Default Output Directory Structure Source: https://ng-openapi.dev/guide/generated-code Illustrates the default file and directory structure generated by ng-openapi when `generateServices` is true and `dateType` is 'Date'. ```tree / ├── models/ │ ├── index.ts # TypeScript interfaces, enums / unions │ └── request-params.ts # Request-object interfaces (only with useSingleRequestParameter) ├── services/ │ ├── index.ts # Service exports │ └── *.service.ts # One Angular service per controller/tag ├── tokens/ │ └── index.ts # Injection tokens for this client ├── utils/ │ ├── base-interceptor.ts # Routes client-scoped interceptors │ ├── date-transformer.ts # Date interceptor (only with dateType: "Date") │ ├── file-download.ts # Download helpers │ └── http-params-builder.ts # Query-param serialization ├── providers.ts # provideClient() setup function └── index.ts # Main barrel export ``` -------------------------------- ### Configure API Client Provider Source: https://ng-openapi.dev/guide/http-resource Set up the API client provider in your Angular application's configuration. ```typescript import { ApplicationConfig } from "@angular/core"; import { provideMyApiClient } from "./api/providers"; export const appConfig: ApplicationConfig = { providers: [ provideMyApiClient({ basePath: "https://api.example.com", }), ], }; ``` -------------------------------- ### Passing Static and Reactive Query Parameters Source: https://ng-openapi.dev/guide/http-resource Combine static and signal-based reactive parameters for fetching data, such as search terms and page sizes. ```typescript import { signal } from "@angular/core"; import { UsersResource } from "./api/resources"; export class SearchComponent { private readonly usersResource = inject(UsersResource); private readonly searchTerm = signal(""); private readonly pageSize = signal(10); readonly searchResults = this.usersResource.searchUsers( this.searchTerm, // reactive search term this.pageSize, // reactive page size "active", // static status filter ); updateSearch(term: string) { this.searchTerm.set(term); } } ``` -------------------------------- ### Angular Component Using downloadFileOperator Source: https://ng-openapi.dev/api/utilities/file-download-helper Demonstrates how to use the `downloadFileOperator` within an Angular component to download a report. Ensure `downloadFileOperator` is imported correctly. ```typescript import { Component, inject } from "@angular/core"; import { downloadFileOperator } from "./api/utils/file-download"; export class ReportComponent { private readonly reportService = inject(ReportService); downloadReport() { this.reportService.getReportById(123).pipe(downloadFileOperator("report.pdf")).subscribe(); } } ``` -------------------------------- ### Configure Orders API Client Source: https://ng-openapi.dev/guide/multiple-clients Define the configuration for generating the Orders API client, specifying input and output paths, and generation options. ```typescript import { GeneratorConfig } from "ng-openapi"; const config: GeneratorConfig = { clientName: "Orders", input: "./orders-swagger.json", output: "./src/api/orders", options: { dateType: "Date", enumStyle: "enum", }, }; export default config; ``` -------------------------------- ### Configure Clients with Interceptors Source: https://ng-openapi.dev/guide/multiple-clients Configure multiple API clients, specifying unique base paths and interceptors for each. This allows for tailored request handling per client. ```typescript export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(), provideUsersClient({ basePath: "https://users-api.example.com", interceptors: [AuthInterceptor], // Only for users API }), provideOrdersClient({ basePath: "https://orders-api.example.com", interceptors: [AuthInterceptor, LoggingInterceptor], // Both interceptors }), ], }; ``` -------------------------------- ### Configure ZodPlugin in OpenAPI Generator Source: https://ng-openapi.dev/api/configuration/plugins/zod Import and include the ZodPlugin in your `openapi.config.ts` file to enable schema generation. This should be a top-level configuration, not nested within `options`. ```typescript import { GeneratorConfig } from 'ng-openapi'; import { ZodPlugin } from '@ng-openapi/zod'; export default { plugins: [ZodPlugin], // top-level, not inside `options` ... // other configurations } as GeneratorConfig; ``` -------------------------------- ### Configure Angular App with API Client Provider Source: https://ng-openapi.dev/getting-started/quick-start Add the necessary provider to your Angular application's configuration file to enable the generated API client. This includes setting the base path for API requests. ```typescript import { ApplicationConfig } from "@angular/core"; import { provideHttpClient } from "@angular/common/http"; import { provideDefaultClient } from "./api/providers"; export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(), provideDefaultClient({ basePath: "https://api.example.com", }), ], }; ``` -------------------------------- ### Register Plugin in Configuration Source: https://ng-openapi.dev/guide/plugin-authoring Users register custom plugin classes in their generator configuration by listing the class name in the 'plugins' array. ```typescript export default { // ... plugins: [MyPlugin], } as GeneratorConfig; ``` -------------------------------- ### NPM Script for Watch Mode Regeneration Source: https://ng-openapi.dev/guide/cli-usage Set up a script to automatically regenerate API clients whenever the OpenAPI specification file changes. This ensures your client code stays up-to-date with the API. ```json { "scripts": { "generate:watch": "nodemon --watch swagger.json --exec 'npm run generate:client'" } } ``` -------------------------------- ### Generate Subcommand Source: https://ng-openapi.dev/api/cli Use the `generate` subcommand for explicit generation tasks. A short alias `gen` is also available. ```bash ng-openapi generate -i swagger.json -o ./src/api ``` ```bash ng-openapi gen -c openapi.config.ts # Short alias ``` -------------------------------- ### Local JSON Input Source: https://ng-openapi.dev/api/configuration/input Specify a local JSON file containing your OpenAPI/Swagger specification. Ensure the file path is correct relative to your configuration file. ```typescript import { GeneratorConfig } from 'ng-openapi'; const config: GeneratorConfig = { input: './swagger.json', ... // other configurations }; export default config; ``` -------------------------------- ### Direct File Download Function Source: https://ng-openapi.dev/guide/file-download Use the `downloadFile` function directly to download a blob with a specified filename, bypassing RxJS operators. This is useful for simple download scenarios. ```typescript import { downloadFile } from "./client/utils/file-download"; // Direct usage without operator this.reportsService.getReportPdf(reportId).subscribe((blob) => { downloadFile(blob, "report.pdf"); }); ``` -------------------------------- ### Basic File Download Operator Source: https://ng-openapi.dev/guide/file-download Use the `downloadFileOperator` to download a file with a predefined filename. This snippet shows basic integration with a service method. ```typescript import { Component, inject } from "@angular/core"; import { downloadFileOperator } from "./client/utils/file-download"; import { ReportsService } from "./client/services"; export class ReportsComponent { private readonly reportsService = inject(ReportsService); downloadReport(reportId: number) { this.reportsService.getReportPdf(reportId).pipe(downloadFileOperator("report.pdf")).subscribe(); } } ``` -------------------------------- ### Client Naming Convention Source: https://ng-openapi.dev/guide/multiple-clients Use descriptive client names that reflect the API purpose. This convention generates corresponding provider functions like `provideUsersClient`. ```typescript clientName: "Users"; // generates provideUsersClient clientName: "Orders"; // generates provideOrdersClient clientName: "Payments"; // generates providePaymentsClient ``` -------------------------------- ### Configure ng-openapi with HttpResourcePlugin Source: https://ng-openapi.dev/guide/http-resource Add the HttpResourcePlugin to your OpenAPI configuration file. ```typescript import { GeneratorConfig } from "ng-openapi"; import { HttpResourcePlugin } from "@ng-openapi/http-resource"; export default { input: "./swagger.json", output: "./src/api", clientName: "MyApi", plugins: [HttpResourcePlugin], options: { dateType: "Date", enumStyle: "enum", }, } as GeneratorConfig; ``` -------------------------------- ### Providing Default Values for Loading States Source: https://ng-openapi.dev/guide/http-resource Supply fallback values to be used while data is loading. ```typescript import { UsersResource } from "./api/resources"; export class UsersComponent { private readonly usersResource = inject(UsersResource); readonly users = this.usersResource.getUsers({ defaultValue: [] }); } ``` -------------------------------- ### Manually Configure Base Path Token Source: https://ng-openapi.dev/guide/angular-integration Manually provide the base path for the ng-openapi client using the `BASE_PATH` token in your Angular application's providers. ```typescript import { BASE_PATH } from "./client/tokens"; export const appConfig: ApplicationConfig = { providers: [{ provide: BASE_PATH, useValue: "https://api.example.com" }], }; ``` -------------------------------- ### Configure ng-openapi Client with Environment Variables Source: https://ng-openapi.dev/guide/angular-integration Configure the ng-openapi client to use an API base path defined in your Angular environment variables. ```typescript import { provideDefaultClient } from "./client/providers"; import { environment } from "./environments/environment"; export const appConfig: ApplicationConfig = { providers: [ provideDefaultClient({ basePath: environment.apiUrl, }), ], }; ``` -------------------------------- ### Configure `validateInput` in `openapi.config.ts` Source: https://ng-openapi.dev/api/configuration/validate-input Use this snippet to configure the `validateInput` function in your `openapi.config.ts` file. It takes the parsed specification object and should return `true` to proceed with generation or `false` to stop. ```typescript import { GeneratorConfig } from 'ng-openapi'; const config: GeneratorConfig = { input: 'https://api.example.com/swagger.json', validateInput: (spec) => { // Example validation: check if the title matches a specific value return spec.info.title === "Swagger Petstore - OpenAPI 3.0"; }, ... // other configurations }; export default config; ``` -------------------------------- ### Extract Filename from Headers and Download Source: https://ng-openapi.dev/guide/file-download This snippet demonstrates how to extract a filename from the `Content-Disposition` header of an HTTP response and then download the file using the extracted name. It requires `HttpClient` and specific utility functions. ```typescript import { HttpClient, HttpResponse } from "@angular/common/http"; import { extractFilenameFromContentDisposition, downloadFile } from "./client/utils/file-download"; export class FilesService { private readonly http = inject(HttpClient); downloadWithHeaders(url: string) { this.http .get(url, { responseType: "blob", observe: "response", }) .subscribe((response: HttpResponse) => { const contentDisposition = response.headers.get("Content-Disposition"); const filename = extractFilenameFromContentDisposition(contentDisposition, "download.pdf"); if (response.body) { downloadFile(response.body, filename); } }); } } ``` -------------------------------- ### Configure HttpResourcePlugin in OpenAPI Generator Source: https://ng-openapi.dev/api/configuration/plugins/http-resource Import and include the HttpResourcePlugin in your OpenAPI generator configuration file (openapi.config.ts). This enables the generation of httpResource services. ```typescript // openapi.config.ts import { GeneratorConfig } from 'ng-openapi'; import { HttpResourcePlugin } from '@ng-openapi/http-resource'; export default { plugins: [HttpResourcePlugin], ... // other configurations } as GeneratorConfig; ``` -------------------------------- ### Configure Client Name in openapi.config.ts Source: https://ng-openapi.dev/api/configuration/client-name Set the `clientName` property in your `openapi.config.ts` file to assign a unique identifier to your generated client. This is essential when you have multiple OpenAPI clients in your project. ```typescript import { GeneratorConfig } from 'ng-openapi'; const config: GeneratorConfig = { clientName: 'PetStore', ... // other configurations }; export default config; ``` -------------------------------- ### Function-Based Filename with Download Operator Source: https://ng-openapi.dev/guide/file-download Use a function within `downloadFileOperator` to generate filenames based on the downloaded blob content and current date. This provides maximum flexibility for naming downloaded files. ```typescript downloadReport(reportId: number) { this.reportsService.getReportPdf(reportId) .pipe( downloadFileOperator((blob: Blob) => { const date = new Date().toISOString().split('T')[0]; return `report-${reportId}-${date}.pdf`; }) ) .subscribe(); } ``` -------------------------------- ### Configure generateEnumBasedOnDescription Source: https://ng-openapi.dev/api/configuration/options/generate-enums-description Set `generateEnumBasedOnDescription` to `true` in your `openapi.config.ts` to enable parsing of JSON descriptions for enum names. Ensure `enumStyle` is set to `enum`. ```typescript import { GeneratorConfig } from 'ng-openapi'; const config: GeneratorConfig = { options: { enumStyle: 'enum', generateEnumBasedOnDescription: true, }, ... // other configurations }; export default config; ``` -------------------------------- ### Configure useSingleRequestParameter Option Source: https://ng-openapi.dev/api/configuration/options/use-single-request-parameter Set the `useSingleRequestParameter` option to `true` in your `openapi.config.ts` file to enable this feature. ```typescript import { GeneratorConfig } from 'ng-openapi'; const config: GeneratorConfig = { options: { useSingleRequestParameter: true }, ... // other configurations }; export default config; ``` -------------------------------- ### Basic Usage of Generated Resources Source: https://ng-openapi.dev/guide/http-resource Inject and use the generated UsersResource in your Angular component to fetch and display users. ```typescript import { Component, inject } from "@angular/core"; import { UsersResource } from "./api/resources"; @Component({ selector: "app-users", template: `
@if (users.isLoading()) {

Loading users...

} @else if (users.error()) {

Error: {{ users.error()?.message }}

} @else { @for (user of users.value(); track user.id) {
{{ user.name }}
} }
`, }) export class UsersComponent { private readonly usersResource = inject(UsersResource); readonly users = this.usersResource.getUsers(); } ``` -------------------------------- ### Provide Client with Custom Date Regex Source: https://ng-openapi.dev/api/providers Configure the default OpenAPI client with a custom regular expression for date transformations. This is useful when your API returns dates in a format not covered by the default pattern. ```typescript provideDefaultClient({ basePath: "https://api.example.com", dateTransformRegex: /your-custom-pattern/, }); ``` -------------------------------- ### Usage with String Dates Source: https://ng-openapi.dev/guide/date-handling When dates are strings, manually create `Date` objects using `new Date()` before performing date-specific operations. ```typescript export class UsersComponent { loadUser(id: number) { this.usersService.getUserById(id).subscribe((user) => { // Convert manually when needed const createdDate = new Date(user.createdAt); console.log(createdDate.getFullYear()); }); } } ``` -------------------------------- ### CompilerOptions Schema Definition Source: https://ng-openapi.dev/api/configuration/compiler-options Defines the structure for TypeScript compiler options that can be configured. ```typescript type CompilerOptions = { declaration?: boolean; target?: ScriptTarget; module?: ModuleKind; strict?: boolean; }; ``` -------------------------------- ### Customizing Date Regex with provideDefaultClient Source: https://ng-openapi.dev/api/utilities/date-transformer Override the default date detection regex when using the generated provider function by passing `dateTransformRegex`. ```typescript provideDefaultClient({ basePath: "https://api.example.com", dateTransformRegex: /your-custom-pattern/, }); ``` -------------------------------- ### Dynamic Filename with Download Operator Source: https://ng-openapi.dev/guide/file-download Dynamically set the filename for downloaded files using template literals within the `downloadFileOperator`. This allows filenames to include dynamic data like report IDs. ```typescript downloadReport(reportId: number) { this.reportsService.getReportPdf(reportId) .pipe( downloadFileOperator(`report-${reportId}.pdf`) ) .subscribe(); } ``` -------------------------------- ### Enable Runtime Response Validation Source: https://ng-openapi.dev/api/configuration/options/validation Configure the `validation.response` option to `true` in your `openapi.config.ts` file to enable runtime validation of API responses. This ensures that data received from the server matches the OpenAPI schema. ```typescript import { GeneratorConfig } from 'ng-openapi'; const config: GeneratorConfig = { options: { validation: { response: true } }, ... // other configurations }; export default config; ``` -------------------------------- ### Use Multiple Services in a Component Source: https://ng-openapi.dev/guide/multiple-clients Inject and utilize services from different API clients within a single Angular component. This demonstrates how to interact with multiple backend services concurrently. ```typescript import { Component, inject } from "@angular/core"; import { toSignal } from "@angular/core/rxjs-interop"; import { UsersService } from "./api/users/services"; import { OrdersService } from "./api/orders/services"; @Component({ selector: "app-dashboard", template: `

Users: {{ users()?.length ?? 0 }}

Orders: {{ orders()?.length ?? 0 }}

`, }) export class DashboardComponent { private readonly usersService = inject(UsersService); private readonly ordersService = inject(OrdersService); readonly users = toSignal(this.usersService.getUsers()); readonly orders = toSignal(this.ordersService.getOrders()); } ``` -------------------------------- ### Enable Automatic Date Transformation Source: https://ng-openapi.dev/guide/date-handling Set `dateType` to 'Date' in `openapi.config.ts` to enable automatic conversion of ISO date strings to Date objects in generated models. ```typescript // openapi.config.ts const config: GeneratorConfig = { options: { dateType: "Date", // Enables automatic transformation }, }; ``` -------------------------------- ### Configure Custom Headers Source: https://ng-openapi.dev/api/configuration/options/custom-headers Define default headers to be included in all HTTP requests. This configuration is part of the `GeneratorConfig` object. ```typescript import { GeneratorConfig } from 'ng-openapi'; const config: GeneratorConfig = { options: { customHeaders: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }, }, ... // other configurations }; export default config; ``` -------------------------------- ### Dynamic Parameter Binding with Signals Source: https://ng-openapi.dev/guide/http-resource Use Angular Signals for reactive parameter binding to automatically refetch data when parameters change. ```typescript import { signal } from "@angular/core"; import { UsersResource } from "./api/resources"; export class UserDetailComponent { private readonly usersResource = inject(UsersResource); private readonly userId = signal(1); // Automatically refetches when userId changes readonly user = this.usersResource.getUserById(this.userId); updateUser(newId: number) { this.userId.set(newId); // Triggers automatic refetch } } ``` -------------------------------- ### Configure Compiler Options in openapi.config.ts Source: https://ng-openapi.dev/api/configuration/compiler-options Set TypeScript compiler options for generated code within your ng-openapi configuration file. Ensure necessary imports are included. ```typescript import { GeneratorConfig, ScriptTarget, ModuleKind } from 'ng-openapi'; const config: GeneratorConfig = { compilerOptions: { declaration: true, target: ScriptTarget.ES2022, module: ModuleKind.Preserve, strict: true }, ... // other configurations }; export default config; ``` -------------------------------- ### Define Logging Interceptor Source: https://ng-openapi.dev/guide/multiple-clients Create an HTTP interceptor to log request details, such as the URL, before the request is sent. This is useful for debugging and monitoring. ```typescript // logging.interceptor.ts import { HttpInterceptor, HttpRequest, HttpHandler } from "@angular/common/http"; import { Injectable } from "@angular/core"; @Injectable() export class LoggingInterceptor implements HttpInterceptor { intercept(req: HttpRequest, next: HttpHandler) { console.log("Request:", req.url); return next.handle(req); } } ``` -------------------------------- ### Configure Response Validation in GeneratorConfig Source: https://ng-openapi.dev/guide/schema-validation Enable response validation by setting `validation.response` to `true` in the `GeneratorConfig`. This prepares the generated client to use validation hooks. ```typescript // users-api.config.ts import { GeneratorConfig } from "ng-openapi"; const config: GeneratorConfig = { clientName: "PetStore", input: "https://petstore3.swagger.io/api/v3/openapi.json", output: "./generated", options: { dateType: "Date", enumStyle: "enum", validation: { response: true, }, }, }; export default config; ``` -------------------------------- ### Define Configuration with GeneratorConfig Type Source: https://ng-openapi.dev/api/configuration Annotate a plain object with the `GeneratorConfig` type for configuration. This method works identically to `defineConfig` and is useful for older versions of ng-openapi. ```typescript // openapi.config.ts import { GeneratorConfig } from "ng-openapi"; const config: GeneratorConfig = { input: "./swagger.json", output: "./src/api", options: { dateType: "Date", enumStyle: "enum", }, }; export default config; ``` -------------------------------- ### Specify Date Type Source: https://ng-openapi.dev/api/cli Control the TypeScript type used for date representations in the generated code. Defaults to `Date`. ```bash ng-openapi -i swagger.json -o ./src/api --date-type string ``` -------------------------------- ### Remote URL Input Source: https://ng-openapi.dev/api/configuration/input Specify a remote HTTP(S) URL pointing to your OpenAPI/Swagger specification in YAML or JSON format. The generator will fetch the specification from this URL. ```typescript const config: GeneratorConfig = { input: 'https://api.example.com/openapi.yaml', ... // other configurations }; ``` -------------------------------- ### Configure Blob Response Type Source: https://ng-openapi.dev/guide/file-download Configure the `responseTypeMapping` in your OpenAPI generator configuration to automatically handle specific MIME types, such as PDF and Excel, as blobs. ```typescript // openapi.config.ts const config: GeneratorConfig = { options: { responseTypeMapping: { "application/pdf": "blob", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "blob", }, }, }; ``` -------------------------------- ### DateInterceptor Source Code Source: https://ng-openapi.dev/api/utilities/date-transformer The core implementation of the DateInterceptor and the transformDates utility function. It uses a default regex to identify and convert ISO date strings in HTTP responses. ```typescript // client/utils/date-transformer.ts import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { Observable } from "rxjs"; import { map } from "rxjs/operators"; export const ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})?$/; export function transformDates(obj: any, dateRegex: RegExp = ISO_DATE_REGEX): any { if (obj === null || obj === undefined || typeof obj !== "object") { return obj; } if (obj instanceof Date) { return obj; } if (Array.isArray(obj)) { return obj.map((item) => transformDates(item, dateRegex)); } if (typeof obj === "object") { const transformed: any = {}; for (const key of Object.keys(obj)) { const value = obj[key]; if (typeof value === "string" && dateRegex.test(value)) { transformed[key] = new Date(value); } else { transformed[key] = transformDates(value, dateRegex); } } return transformed; } return obj; } @Injectable() export class DateInterceptor implements HttpInterceptor { /** @param dateRegex Optional override for the pattern used to detect ISO date strings. */ constructor(private readonly dateRegex: RegExp = ISO_DATE_REGEX) {} intercept(req: HttpRequest, next: HttpHandler): Observable> { return next.handle(req).pipe( map((event) => { if (event instanceof HttpResponse && event.body) { return event.clone({ body: transformDates(event.body, this.dateRegex) }); } return event; }), ); } } ``` -------------------------------- ### Custom Date Regex for Interceptor and Transformer Source: https://ng-openapi.dev/guide/date-handling Instantiate `DateInterceptor` or call `transformDates` with a custom regex to handle specific date formats not covered by the default pattern. ```typescript new DateInterceptor(/your-custom-regex/); transformDates(responseBody, /your-custom-regex/); ``` -------------------------------- ### downloadFileOperator RxJS Operator Source: https://ng-openapi.dev/api/utilities/file-download-helper This RxJS operator wraps the `downloadFile` function, allowing it to be used within an Observable pipe. It supports dynamic filename generation via a callback. ```typescript export function downloadFileOperator( filename: string | ((blob: T) => string), mimeType?: string, ): (source: Observable) => Observable { return (source: Observable) => { return source.pipe( tap((blob: T) => { const actualFilename = typeof filename === "function" ? filename(blob) : filename; downloadFile(blob, actualFilename, mimeType); }), ); }; } ``` -------------------------------- ### Generate Only Types Source: https://ng-openapi.dev/api/cli Generate only TypeScript interfaces without services. This is useful when you only need data structures. ```bash ng-openapi -i swagger.json -o ./src/api --types-only ``` -------------------------------- ### Generated Model with String Type Source: https://ng-openapi.dev/guide/date-handling With `dateType` set to 'string', date fields in generated interfaces remain as ISO strings, requiring manual conversion to `Date` objects when needed. ```typescript // Generated interface with string type interface User { id: number; name: string; createdAt: string; // ISO string format updatedAt: string; } ``` -------------------------------- ### Usage with Automatic Date Transformation Source: https://ng-openapi.dev/guide/date-handling In components, `Date` objects are directly usable, allowing methods like `getFullYear()` and `toLocaleDateString()` to be called without manual conversion. ```typescript export class UsersComponent { private readonly usersService = inject(UsersService); loadUser(id: number) { this.usersService.getUserById(id).subscribe((user) => { // createdAt is already a Date object console.log(user.createdAt.getFullYear()); console.log(user.createdAt.toLocaleDateString()); }); } } ``` -------------------------------- ### extractFilenameFromContentDisposition Function Source: https://ng-openapi.dev/api/utilities/file-download-helper Extracts a filename from a Content-Disposition header string. It supports both 'filename=' and 'filename*=' formats and handles RFC 5987 encoding. ```typescript export function extractFilenameFromContentDisposition( contentDisposition: string | null, fallbackFilename: string = "download", ): string { if (!contentDisposition) { return fallbackFilename; } // Try to extract filename from Content-Disposition header // Supports both "filename=" and "filename*=" formats const filenameMatch = contentDisposition.match(/filename\*?=['"]?([^'"\n;]+)['"]?/i); if (filenameMatch && filenameMatch[1]) { // Decode if it's RFC 5987 encoded (filename*=UTF-8''...) const filename = filenameMatch[1]; if (filename.includes("''")) { const parts = filename.split("''"); const encoded = parts.length === 2 ? parts[1] : undefined; if (encoded) { try { return decodeURIComponent(encoded); } catch { return encoded; } } } return filename; } return fallbackFilename; } ```