change over primeng v22

This commit is contained in:
Kham
2026-09-18 15:19:16 +10:00
parent f74125a92c
commit 3807524412
108 changed files with 17705 additions and 84 deletions
+60
View File
@@ -0,0 +1,60 @@
import { FormControl, FormGroup } from '@angular/forms';
declare global {
interface Navigator {
msSaveBlob?: (blob: any, defaultName?: string) => boolean
msSaveOrOpenBlob?: (blob: any, defaultName?: string) => boolean
}
}
export class CommonUtilities {
/** Display the blob */
static displayFileInNewTab(response: any, defaultFileName: string) {
const contentType = response.headers.get('content-type');
const blob = new Blob([response.body], { type: contentType });
const fileName = this.getFileName(response, defaultFileName);
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
const data = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = data;
link.target = '_blank';
link.click();
}
}
/*** Download the blob ***/
static downloadFile(response: any, defaultFileName: string) {
const contentType = response.headers.get('content-type');
const blob = new Blob([response.body], { type: contentType });
const fileName = this.getFileName(response, defaultFileName);
if (typeof window.navigator.msSaveBlob === 'function') {
console.log("download the report saveblob");
window.navigator.msSaveBlob(blob, fileName);
console.log("download the report saveblob done");
}
else {
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
console.log("no msSaveBlob download the report saveblob done");
//link.download? = fileName;
link.download = fileName;
link.click();
}
}
/** Get the attachment file name */
static getFileName(response: any, defaultFileName: string) {
const contentDis = response.headers.get('content-disposition');
let fileName = defaultFileName;
if (contentDis && contentDis.indexOf('attachment') !== -1) {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(contentDis);
if (matches != null && matches[1]) {
fileName = matches[1].replace(/['"]/g, '');
}
}
return fileName;
}
}
+65
View File
@@ -0,0 +1,65 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
export function initializeApp() {
return (): Promise<any> => {
return inject(AppSettingService).loadAppSetting();
}
// return () => inject(AppSettingService).loadAppSetting();
};
@Injectable({ providedIn: 'root' })
export class AppSettingService {
private _appsetting: any;
constructor(private http: HttpClient
) { }
public loadAppSetting(): Promise<any> {
const source$ = this.http.get("config/appsetting.json")
const rs$ = firstValueFrom(source$)
.then(x => {
this._appsetting = x;
console.log("[AppSettingService] assign", x);
return x;
});
return rs$;
}
set appSeting(value: any) {
this._appsetting = value;
}
get appSetting(): any {
return this._appsetting;
}
}
/* module put this
to use it
in app.module.ts
add
1)
providers: [
{ provide : APP_INITIALIZER, multi : true, deps : [AppSettingService],
useFactory: initializeApp
},
]
2)
other this one work too.
providers: [
{
provide : APP_INITIALIZER,
multi : true,
deps : [AppSettingService],
useFactory : (appConfigService : AppSettingService) => () => appConfigService.loadAppSetting()
}
]
to use it calling something like this
export class TestComponent {
public test1ServiceUrl: string;
constructor(public configService: AppConfigService) {
this.test1ServiceUrl = this.configService.appSetting.test1ServiceUrl;
}
}
*/
+97
View File
@@ -0,0 +1,97 @@
import { Injectable, inject } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpInterceptorFn, HttpHandlerFn } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthenticationService } from '../user-services';
//import { ToastrService } from 'ngx-toastr';
import { NavigationExtras, Router } from '@angular/router';
/*
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
//private authenticationService: AuthenticationService;
constructor(
private router: Router,
// private toastr: ToastrService,
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// console.log("I am intercept to catch error status = 401...", request);
return next.handle(request).pipe(catchError(err => {
/* no use yet
if (err) {
switch(err.status) {
case 400:
if (err.error.errors) {
const modalStateErrors = [];
for (const key in err.error.errors) {
if (err.error.errors[key]) {
modalStateErrors.push(err.error.errors[key]);
}
}
throw modalStateErrors;
} else {
this.toastr.error(err.statusText, err.status);
}
break;
case 401:
this.toastr.error(err.statusText, err.status);
break;
case 404:
this.router.navigateByUrl('/not-found');
break;
case 500:
const navigationExtras: NavigationExtras = {state:{error:err.error}};
this.router.navigateByUrl('/server-error', navigationExtras);
break;
default:
this.toastr.error('Something unexpected went wrong');
console.log("this error interceptor",err);
break;
}
}
*/
/*
if (err.status === 401) {
// auto logout if 401 response returned from api Unauthorized
// this.authenticationService.logout();
//location.reload();
const error = err.error.message || err.statusText;
console.log("After I Get Error status = 401...", error, err);
return throwError(error);
}
else {
console.log("I Get Error .", err);
return throwError(err);
}
}))
}
}
*/
//new one
//https://blog.ninja-squad.com/2022/11/09/angular-http-in-standalone-applications/
////////////////
export const ErrorInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> => {
const authenticationService = inject(AuthenticationService);
// logger.log(`Request is on its way to ${req.url}`);
return next(req).pipe(catchError(err => {
if (err.status === 401) {
// auto logout if 401 response returned from api Unauthorized
// this.authenticationService.logout();
//location.reload();
const error = err.error.message || err.statusText;
// console.log("After I Get Error status = 401...", error, err);
return throwError(() => error);
}
else {
console.log("I Get Error .", err);
return throwError(() => err);
}
}));
}
////////////////
+115
View File
@@ -0,0 +1,115 @@
import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ConfigureUrl } from '../models';
import { AppSettingService } from './appsetting';
@Injectable({
providedIn: 'root'
})
export class HttpUtility {
private baseApiUrl: string = "";
constructor(private http: HttpClient,
private appSetting :AppSettingService,
private router: Router) {
}
/**
* getFile
* @param url
*/
public getFileAsText(url: string): Observable<any> {
return this.http
.get(this.getApiUrl(url), { responseType: 'blob' as 'text' })
.pipe(catchError(e => this.handleError(e)));
}
/**
* getFile
* @param url
*/
public getFile(url: string): Observable<any> {
return this.http
.get(this.getApiUrl(url), { responseType: 'blob' as 'json' })
.pipe(catchError(e => this.handleError(e)));
}
/**
* handleError
* @param response
*/
private handleError(errorResponse: HttpErrorResponse) {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
return throwError(errorResponse);
}
//get excel file zip file etc ..
/*
allowedToDisplay = [
this.mimeConstant.png,
this.mimeConstant.jpeg,
this.mimeConstant.jpg,
this.mimeConstant.gif,
this.mimeConstant.txt,
this.mimeConstant.pdf
];
*/
/* how to use it
this.http.getFileResponse(`Person/GetPhoto?recordId=${personId}`).pipe(
catchError(err => {
this.snackBar.error(err || this.constants.error_Getting_photo);
return EMPTY;
}),
finalize(() => {
this.spinner.hide();
})).subscribe(response => {
if (response) {
if (isDownload) {
CommonUtilities.downloadFile(response);
} else {
if (response.body && response.body.type) {
if (this.allowedToDisplay.includes(response.body.type)) {
CommonUtilities.displayFileInNewTab(response);
} else {
this.temporaryFile = response;
this.downloadWarning = true;
}
}
}
}
});
*/
public getFileResponse(url: string, data?: any): Observable<any> {
if (data) {
return this.http.post(this.getApiUrl(url),
data,
{ responseType: 'blob', observe: 'response' })
.pipe(catchError(e => this.handleError(e)));
}
return this.http
.get(this.getApiUrl(url), { responseType: 'blob', observe: 'response' })
.pipe(catchError(e => this.handleError(e)));
}
public getFileAsPDF(url: string, data: any): Observable<any> {
let updateURL;
if (data) {
updateURL = url + data;
} else {
updateURL = url;
}
return this.http
.get(this.getApiUrl(updateURL), { responseType: 'blob' as 'text', observe: 'response' })
.pipe(catchError(e => this.handleError(e)));
}
/**
* getApiUrl
* @param url
*/
private getApiUrl(url:string) {
const baseUrl = this.appSetting.appSetting.baseUrl;
return baseUrl + "/"+ url;
}
}
+8
View File
@@ -0,0 +1,8 @@
export * from './lookup.service';
export * from './utils';
export * from './httpfile.service';
export * from './CommonUtilities';
export * from './error.interceptor';
export * from './jwt.interceptor';
export { initializeApp, AppSettingService } from './appsetting';
+50
View File
@@ -0,0 +1,50 @@
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpInterceptorFn, HttpHandlerFn } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Utils } from './utils';
/*
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
const currentUser = Utils.getCurrentUser();//localStorage.getItem('currentUser')!;
console.log('I am interceptor debug for currentUser obj', currentUser);
if (currentUser && currentUser.token) {
//console.log('I am interceptor add authorization header with jwt token');
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}
return next.handle(request);
}
}
/*
new one
////////////////
*/
export const JwtInterceptor: HttpInterceptorFn = (request: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> => {
//const logger = inject(Logger);
//logger.log(`Request is on its way to ${req.url}`);
let data: any = {
withCredentials: true
}
const currentUser = Utils.getCurrentUser();//localStorage.getItem('currentUser')!;
// console.log('I am interceptor debug for currentUser obj', currentUser);
if (currentUser && currentUser.token && currentUser.token != "") {
// console.log('I am interceptor add authorization header with jwt token');
data.setHeaders = {
Authorization: `Bearer ${currentUser.token}`
};
}
request = request.clone(data);
return next(request);
}
////////////////
/*
providers: [provideHttpClient(withInterceptors([loggerInterceptor]))]
*/
+25
View File
@@ -0,0 +1,25 @@
import { Injectable, Inject } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ConfigureUrl,Lookup,ResultModel } from '../models';
import { AppSettingService } from '../shares';
@Injectable({ providedIn: 'root' })
export class LookupService {
constructor(private http: HttpClient,
private appSetting :AppSettingService
) {}
loadConcessionType(): Observable<ResultModel<Lookup[]>> {
const url = this.appSetting.appSetting.baseUrl +"/"+ConfigureUrl.luConcessionTypeUrl;
return this.http.get<ResultModel<Lookup[]>>(url);
}
loadValidationPoint(): Observable<ResultModel<Lookup[]>> {
const url = this.appSetting.appSetting.baseUrl +"/"+ConfigureUrl.luValidationPointUrl;
return this.http.get<ResultModel<Lookup[]>>(url);
}
}
+66
View File
@@ -0,0 +1,66 @@
import { User, userRole } from "../models"
export class Utils {
static getCurrentUser(): User {
let myUser = new User();
myUser.username = "";
const obj = sessionStorage.getItem('currentUser');
//const obj = localStorage.getItem('currentUser');
if (obj != undefined) {
let user = JSON.parse(obj);
myUser.firstName = user.firstName;
myUser.lastName = user.lastName;
myUser.role = user.role;
myUser.username = user.username;
myUser.email = user.email;
myUser.token = user.token;
myUser.validationPointId = user.validationPointId;
}
// console.log("[util] getcurrentUser",myUser);
return myUser;
}
static setLocalStore(user: User): void {
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
// localStorage.setItem('currentUser', JSON.stringify(user));
sessionStorage.setItem('currentUser', JSON.stringify(user));
}
}
static getUserRole(user: User): string {
let ret: string;
if (user.role == userRole.Normal)
ret = "Normal";
else (user.role == userRole.Admin)
ret = "Admin";
return ret;
}
static getIsAuth(): boolean {
const user = this.getCurrentUser();
if (user.username != "") {
return true;
}
else
return false;
}
static getIsAdmin(): boolean {
const user = this.getCurrentUser();
let result = false;
// console.log("[util] get isAdmin", user);
if (user.username != "") {
// console.log("[util] get isAdmin username is not null", user);
if (user.role == userRole.Admin)
// console.log("[util] this user is admin", user);
result = user.role == userRole.Admin;
}
else
result = false;
return result;
}
static clearCurrentUser(): void {
sessionStorage.clear();
//localStorage.clear();
}
}