Skip to main content

Overview

The BackendService is the main service for handling backend API operations in the Angular PWA Demo. It extends BaseService and implements OnInit, providing methods for logging, CSV/Excel file generation, and data retrieval from multiple backend technologies including .NET Core, Node.js, Spring Boot, and Django.
This service showcases Angular 21’s functional dependency injection pattern using the inject() function instead of constructor-based injection.

Service configuration

import { inject } from '@angular/core';
import { BackendService } from './_services/BackendService/backend.service';

export class AppComponent {
  private readonly backendService = inject(BackendService);
  
  ngOnInit(): void {
    const baseUrl = this._configService.getConfigValue('baseUrlNetCore');
    if (baseUrl) {
      this.backendService._SetSTATPieCache(baseUrl);
      this.backendService._SetSTATBarCache(baseUrl);
    }
  }
}

Dependencies

The service uses Angular 21’s functional injection:
http
HttpClient
required
Injected using inject(HttpClient) for making HTTP requests
_configService
ConfigService
required
Injected using inject(ConfigService) for configuration values
destroyRef
DestroyRef
required
Injected using inject(DestroyRef) for managing subscriptions lifecycle
export class BackendService extends BaseService implements OnInit {
  // v21: Functional injection (replaces constructor injection)
  public readonly http           = inject(HttpClient);
  public readonly _configService = inject(ConfigService);
  private readonly destroyRef    = inject(DestroyRef);

  constructor() {
    super();
  }
}

Common methods

_GetWebApiAppVersion

Retrieves the .NET Core Web API application version.
_GetWebApiAppVersion(): Observable<string>
Returns: An Observable<string> containing the API version. Usage example:
this.backendService._GetWebApiAppVersion()
  .subscribe({
    next: (version) => console.log('API Version:', version),
    error: (err) => console.error('Error:', err)
  });

_GetASPNETCoreCppVersion

Retrieves the ASP.NET Core C++ entry point version.
_GetASPNETCoreCppVersion(): Observable<string>
Returns: An Observable<string> containing the C++ API version.

SetLog

Logs application events to the backend server.
SetLog(p_PageTitle: string, p_logMsg: string, logType: LogType = LogType.Info): void
p_PageTitle
string
required
The title of the page where the log originated
p_logMsg
string
required
The log message to record
logType
LogType
default:"LogType.Info"
The type of log entry (Info, Warning, Error)
This method uses takeUntilDestroyed(this.destroyRef) to prevent the NG0203 error when called asynchronously outside the constructor.
Usage example:
import { LogType } from 'src/app/_models/entity.model';

this.backendService.SetLog(
  'Home Page',
  'User logged in successfully',
  LogType.Info
);

CSV file generation

Retrieves a link to a generated CSV file.
getCSVLink(): Observable<string>
Returns: An Observable<string> containing the CSV file URL.

getInformeRemotoCSV

Generates a CSV report from the .NET Core backend.
getInformeRemotoCSV(): Observable<string>
Returns: An Observable<string> containing the CSV data.

getInformeRemotoCSV_STAT

Generates a statistical CSV report from cached data.
getInformeRemotoCSV_STAT(): Observable<string>
Returns: An Observable<string> containing the statistical CSV data.

_SetSTATPieCache

Caches statistical pie chart data on the backend.
_SetSTATPieCache(_prefix: string | undefined): void
_prefix
string | undefined
required
The base URL prefix for the API endpoint
Usage example:
private setupCache(): void {
  const baseUrl = this._configService.getConfigValue('baseUrlNetCore');
  if (baseUrl) {
    this.backendService._SetSTATPieCache(baseUrl);
  }
}

getInformeRemotoCSV_NodeJS

Generates a CSV report from the Node.js backend.
getInformeRemotoCSV_NodeJS(): Observable<string>
Returns: An Observable<string> containing the CSV data from Node.js.

Excel file generation

getLogRemoto

Retrieves log entries from the .NET Core backend.
getLogRemoto(_searchCriteria: SearchCriteria): Observable<LogEntry[]>
_searchCriteria
SearchCriteria
required
Search criteria object containing date range and filters
Returns: An Observable<LogEntry[]> containing the log entries. Real-world usage:
public searchLogs(searchCriteria: SearchCriteria): void {
  this.backendService.getLogRemoto(searchCriteria)
    .subscribe({
      next: (logEntries: LogEntry[]) => {
        this.dataSource = new MatTableDataSource<LogEntry>(logEntries);
        this.dataSource.paginator = this.paginator;
        this.statusMessage.set(`[${logEntries.length}] records found`);
      },
      error: (err: Error) => {
        console.error('Error fetching logs:', err.message);
        this.statusMessage.set('An error occurred. Please try again');
      },
      complete: () => {
        this.buttonCaption = '[Search]';
      }
    });
}

getLogRemotoNodeJS

Retrieves log entries from the Node.js backend.
getLogRemotoNodeJS(_searchCriteria: SearchCriteria): Observable<string>
Returns: An Observable<string> containing JSON log data from Node.js. Usage example:
this.backendService.getLogRemotoNodeJS(searchCriteria)
  .subscribe({
    next: (logData: string) => {
      const logEntries = JSON.parse(logData)['recordsets'][0];
      this.dataSource = new MatTableDataSource<LogEntry>(logEntries);
    }
  });

getLogRemotoSprinbBootJava

Retrieves log entries from the Spring Boot (Java) backend.
getLogRemotoSprinbBootJava(_searchCriteria: SearchCriteria): Observable<string>
Returns: An Observable<string> containing JSON log data from Spring Boot.

getPersonsSprinbBootJava

Retrieves person records from the Spring Boot backend.
getPersonsSprinbBootJava(): Observable<string>
Returns: An Observable<string> containing JSON person data.

getLogRemotoDjangoPython

Retrieves log entries from the Django (Python) backend.
getLogRemotoDjangoPython(_searchCriteria: SearchCriteria): Observable<string>
Returns: An Observable<string> containing JSON log data from Django.

getInformeExcel

Generates an Excel file from the .NET Core backend.
getInformeExcel(_searchCriteria: SearchCriteria): Observable<string>
_searchCriteria
SearchCriteria
required
Search criteria for the Excel report
Returns: An Observable<string> containing the Excel file name. Real-world usage:
public generateExcelReport(searchCriteria: SearchCriteria): void {
  this.backendService.getInformeExcel(searchCriteria)
    .subscribe({
      next: (excelFileName: string) => {
        const urlFile = UtilManager.DebugHostingContent(excelFileName);
        this.excelDownloadLink = `${this.configService.getConfigValue('baseUrlNetCore')}/wwwroot/xlsx/${urlFile}`;
        this.statusMessage.set('[XLS file generated correctly]');
        this.downloadLinkText = '[Download XLS File]';
      },
      error: (err: Error) => {
        console.error('Error generating Excel:', err.message);
        this.statusMessage.set('[An error occurred]');
      }
    });
}

getPersonsDjangoPython

Retrieves person records from the Django backend.
getPersonsDjangoPython(): Observable<string>
Returns: An Observable<string> containing JSON person data from Django.

getLogStatGET

Retrieves statistical log data from the .NET Core backend cache.
getLogStatGET(): Observable<string>
Returns: An Observable<string> containing JSON statistical data.

_SetSTATBarCache

Caches statistical bar chart data on the backend.
_SetSTATBarCache(_prefix: string | undefined): void
_prefix
string | undefined
required
The base URL prefix for the API endpoint

Angular 21 features

This service demonstrates several Angular 21 best practices:
Uses inject() function instead of constructor parameters:
public readonly http = inject(HttpClient);
public readonly _configService = inject(ConfigService);
private readonly destroyRef = inject(DestroyRef);

Multi-backend support

The service communicates with multiple backend technologies:

.NET Core / C#

Primary backend for most operations including file generation and logging.

Node.js / JavaScript

Alternative backend for CSV and log data retrieval.

Spring Boot / Java

Backend for Java-based log and person data operations.

Django / Python

Backend for Python-based log and person data operations.

Best practices

1

Use takeUntilDestroyed

Always use takeUntilDestroyed(this.destroyRef) for subscriptions to prevent memory leaks.
2

Handle errors gracefully

Implement error handlers in all subscriptions to provide user feedback.
3

Validate inputs

Check for empty or null parameters before making API calls.
4

Update UI status

Keep users informed during long-running operations like file generation.

Source location

~/workspace/source/src/app/_services/BackendService/backend.service.ts

Build docs developers (and LLMs) love