Skip to content

DNext Angular HTTP Library

The @dnext-angular/http library provides a set of utilities to simplify HTTP requests and authentication in Angular applications.

Installation

To install the library, use npm:

npm install @dnext-angular/http

Setup

Basic Setup

Import the necessary modules and services in your Angular application:

import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AuthorizationService, HttpHelperService } from '@dnext-angular/http';

@NgModule({
  imports: [
    HttpClientModule
  ],
  providers: [
    AuthorizationService,
    HttpHelperService
  ]
})
export class AppModule { }

Configuration Setup

Create a configuration file (e.g., auth-config.ts):

import { IConfig } from '@dnext-angular/http';

export const authConfig: IConfig = {
  authRequired: true,
  baseURI: 'https://api.example.com',
  auth: {
    scope: 'openid profile email',
    responseType: 'code',
    issuer: 'https://your-issuer.com',
    redirectUri: window.location.origin,
    strictDiscoveryDocumentValidation: false,
    clientId: 'your-client-id',
    dummyClientSecret: 'your-client-secret'
  }
};

Implementation Examples

1. Authentication Guard

Create an authentication guard to protect routes:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthorizationService } from '@dnext-angular/http';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(
    private authService: AuthorizationService,
    private router: Router
  ) {}

  async canActivate(): Promise<boolean> {
    try {
      const isAuthenticated = await this.authService.setupAuthentication();
      if (!isAuthenticated) {
        this.router.navigate(['/login']);
        return false;
      }
      return true;
    } catch (error) {
      console.error('Authentication error:', error);
      return false;
    }
  }
}

2. Authentication Service Implementation

Create a service to handle authentication:

import { Injectable } from '@angular/core';
import { AuthorizationService } from '@dnext-angular/http';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private isAuthenticatedSubject = new BehaviorSubject<boolean>(false);
  isAuthenticated$ = this.isAuthenticatedSubject.asObservable();

  constructor(private authService: AuthorizationService) {
    this.checkAuthStatus();
  }

  async checkAuthStatus() {
    try {
      const isAuthenticated = await this.authService.setupAuthentication();
      this.isAuthenticatedSubject.next(isAuthenticated);
    } catch (error) {
      console.error('Auth status check failed:', error);
      this.isAuthenticatedSubject.next(false);
    }
  }

  async login() {
    try {
      await this.authService.setupAuthentication();
    } catch (error) {
      console.error('Login failed:', error);
      throw error;
    }
  }

  logout() {
    this.authService.logOut();
    this.isAuthenticatedSubject.next(false);
  }

  getToken(): string {
    return this.authService.getAccessToken();
  }
}

3. HTTP Service Implementation

Create a service to handle HTTP requests:

import { Injectable } from '@angular/core';
import { HttpHelperService } from '@dnext-angular/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private httpHelper: HttpHelperService) {}

  getData<T>(endpoint: string, params?: any): Observable<T> {
    return this.httpHelper.get<T>(endpoint, params);
  }

  postData<T>(endpoint: string, data: any): Observable<T> {
    return this.httpHelper.post<T>(endpoint, undefined, data);
  }

  updateData<T>(endpoint: string, data: any): Observable<T> {
    return this.httpHelper.patch<T>(endpoint, undefined, data);
  }

  deleteData(endpoint: string): Observable<void> {
    return this.httpHelper.delete(endpoint);
  }
}

4. Component Implementation Example

import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
import { AuthService } from './auth.service';

@Component({
  selector: 'app-protected-page',
  template: `
    <div *ngIf="isAuthenticated$ | async">
      <h2>Protected Content</h2>
      <button (click)="fetchData()">Fetch Data</button>
      <button (click)="logout()">Logout</button>

      <div *ngIf="data">
        {{ data | json }}
      </div>
    </div>
  `
})
export class ProtectedPageComponent implements OnInit {
  isAuthenticated$ = this.authService.isAuthenticated$;
  data: any;

  constructor(
    private authService: AuthService,
    private apiService: ApiService
  ) {}

  ngOnInit() {
    this.checkAuth();
  }

  async checkAuth() {
    await this.authService.checkAuthStatus();
  }

  fetchData() {
    this.apiService.getData('/api/protected-data').subscribe({
      next: (response) => {
        this.data = response;
      },
      error: (error) => {
        console.error('Error fetching data:', error);
      }
    });
  }

  logout() {
    this.authService.logout();
  }
}

5. Route Configuration

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  {
    path: 'protected',
    component: ProtectedPageComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'login',
    component: LoginComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Error Handling

import { Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ErrorHandlingService {
  handleError(error: HttpErrorResponse) {
    let errorMessage = 'An unknown error occurred!';

    if (error.error instanceof ErrorEvent) {
      // Client-side error
      errorMessage = `Error: ${error.error.message}`;
    } else {
      // Server-side error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }

    console.error(errorMessage);
    return throwError(() => new Error(errorMessage));
  }
}

// Usage in API Service
this.httpHelper.get(endpoint).pipe(
  catchError(this.errorHandling.handleError)
);

Dependencies

  • @angular/core: >=18.0.1
  • @angular/common: >=18.0.1
  • angular-oauth2-oidc: 17.0.2
  • rxjs: ~7.8.0

License

DNext PiAGroup