Skip to content

Instantly share code, notes, and snippets.

@anytizer
Last active December 1, 2023 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anytizer/2208105baf043cdca69cec4ac6be11c5 to your computer and use it in GitHub Desktop.
Save anytizer/2208105baf043cdca69cec4ac6be11c5 to your computer and use it in GitHub Desktop.
Making an API Client Consumer Website in Angular

api.service.ts

import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { IDValueDTO } from './dtos';

@Injectable({
  providedIn: "root"
})
export class APIService {
  private gateway = "https://localhost:7257";
  private headers = new HttpHeaders();

  private endpoints = {
    "fruits_list": "api/fruits/list",
    "fruits_remove": "api/fruits/remove",
  };
    
  constructor(private http: HttpClient, private ck: CookieService) {

    let token = this.ck.get("token"); // only set/unset by the login script

    this.headers = this.headers
      .set("Content-Type", "application/json; charset=utf-8")
      .set("X-Protection-Token", token)
    ;
  };

  private post(endpoint: string, data={}) { return this.http.post<any>(this.gateway+endpoint, data, {headers: this.headers}); }
  
  public fruits_list():Observable<any> { return this.post(this.endpoints.fruits_list, []); }
  public fruits_remove(fruit: IDValueDTO): Observable<any> { return this.post(this.endpoints.fruits_remove, fruit); }
};
import { ApplicationConfig, NgModule } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideHttpClient, withFetch } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes), provideHttpClient(withFetch()),]
};
export class IDValueDTO
{
  id: string = "";
  value: string = "";
}

Starting Angular project

Install NPM (nodejs)

Install nodejs

Install Angular CLI

npm install -g @angular/cli
npm install -g ngx-cookie-service

Use Angular Language Service extension in visual studio

Install Angular in local

mkdir -p websites/www/src
cd websites/www/src
ng new client --routing --style=scss
cd client

Generate components

(It will take a little while)

ng generate environments

ng g c home
ng g c dashboard
ng g c login
ng g c logout
ng g c pagenotfound

Create API service

ng g s api

Start angular project

npm start
ng serve

Fix homepage contents

From src/app/app.component.html: delete everything and put the following content:

<h1>Project Name</h1>

<ul>
    <li><a href="#" [routerLink]="['home']">Home</a></li>
    <li><a href="#" [routerLink]="['dashboard']">Dashboard</a></li>
    <li><a href="#" [routerLink]="['pagenotfound']">Page Not Found!</a></li>
    <li><a href="#" [routerLink]="['login']">Login</a></li>
    <li><a href="#" [routerLink]="['logout']">Logout</a></li>
</ul>

<router-outlet></router-outlet>

Edit routing module

Edit the routing module with nano app.routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { LogoutComponent } from './logout/logout.component';
import { PagenotfoundComponent } from './pagenotfound/pagenotfound.component';

const routes: Routes = [
  {path: '', redirectTo: "home", pathMatch: "full"},
  {path: 'home', component: HomeComponent},
  {path: 'dashboard', component: DashboardComponent},
  {path: 'login', component: LoginComponent},
  {path: 'logout', component: LogoutComponent},
  {path: '**', component: PagenotfoundComponent},
];

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

api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { SuccessStatusDTO, LoginResponseDTO } from './objects';
import { CookieService } from 'ngx-cookie-service';

class Endpoints
{
    public test_menus: string = "/api/tests/links";
    public users_apply: string = "/api/users/apply";
    public users_login: string = "/api/users/login";
    public applications_list: string = "/api/applications/list";
    public roles_list: string = "/api/roles/list";
    public roles_delete: string = "/api/roles/delete";
    public roles_create: string = "/api/roles/create";
    public roles_edit: string = "/api/roles/edit";
}

@Injectable({
providedIn: "root"
})
export class APIService {

  // https://localhost:7257/api/values/links
  private gateway = "https://localhost:7257";
  private headers = new HttpHeaders();
  private endpoints = new Endpoints();

  constructor(private http: HttpClient, private ck: CookieService) {

    let token = this.ck.get("token"); // set by login script

    this.headers = this.headers
      .set("Content-Type", "application/json; charset=utf-8")
      .set("X-Protection-Token", token)
    ;
 };

 private post(endpoint: string, data={}) { return this.http.post<any>(this.gateway+endpoint, data, {headers: this.headers}); }

public users_login(login: LoginDTO): Observable { return this.post(this.endpoints.users_login, login);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment