import { Injectable, Injector, Inject } from '@angular/core'; // import { map } from 'rxjs/operators' import { HttpClient, HttpHeaders } from '@angular/common/http'; // import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http'; import { IEnvironmentsInfo } from '../Models/environmentsModel.info'; import { Observable, throwError,map, lastValueFrom } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class BaseService { //private API_ENDPOINT = AppSettings.CBMS_SERVICES_URL; private API_ENDPOINT: string; private RM_ENDPOINT: string; private config: IEnvironmentsInfo; private headers: HttpHeaders; private postheaders: HttpHeaders; public http: HttpClient; private getConfig() { if (!this.config) { try { this.config = this.injector.get('config' as any); this.API_ENDPOINT = this.config?.CBMSServiceUrl || ''; this.RM_ENDPOINT = this.config?.apiBaseUrl || ''; } catch (error) { console.warn('Config not available:', error); return false; } } return true; } constructor(public injector: Injector) { try { this.config = this.injector.get('config' as any); this.API_ENDPOINT = this.config?.CBMSServiceUrl || ''; this.RM_ENDPOINT = this.config?.apiBaseUrl || ''; } catch (error) { // Config not available, use empty strings this.API_ENDPOINT = ''; this.RM_ENDPOINT = ''; } this.headers = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }); this.postheaders = new HttpHeaders({'Content-Type': 'application/json'}); this.http = this.injector.get(HttpClient); // Fix: Remove invalid 'application/jsonp' content type - this was causing the issue // this.headers = this.headers.set('Content-Type', 'application/jsonp'); // console.log("config",this.injector.get("config")) } //private options = new RequestOptions({headers: this.headers}); // private requestOptions = new RequestOptions({ method: RequestMethod.Post, headers: this.postheaders }); public get(path) { if (!this.getConfig() || !this.API_ENDPOINT) { return throwError(() => new Error('Configuration not available')); } //alert(this.API_ENDPOINT + path); return this.http.get(this.API_ENDPOINT + path) .pipe(map(this.extractData)) // .map(this.extractData) // .catch(error => { // return this.handleError(error || 'Error while executing GET for route ' + path); // }); } public getApi(path) { return this.http.get(this.API_ENDPOINT + path,{headers: this.headers}) .pipe(map(this.extractData)) // .map(this.extractData) // .catch(error => { // return this.handleError(error || 'Error while executing GET for route ' + path); // }); } public postData(path, data) { // Debug specifically for ValidateUid requests if (path.includes('ValidateUid')) { console.log('=== ValidateUid Request Debug ==='); console.log('postData - path:', path); console.log('postData - data:', data); console.log('postData - headers being sent:', this.postheaders); console.log('postData - API_ENDPOINT:', this.API_ENDPOINT); console.log('postData - full URL:', this.API_ENDPOINT + path); console.log('=== End ValidateUid Request Debug ==='); } return this.http.post(this.API_ENDPOINT + path, data, {headers: this.postheaders}) .pipe(map((response: any) => { // Debug specifically for ValidateUid responses if (path.includes('ValidateUid')) { console.log('=== ValidateUid Response Debug ==='); console.log('postData - response:', response); console.log('postData - response type:', typeof response); console.log('=== End ValidateUid Response Debug ==='); } return response; })) // .catch(error => { // return this.handleError(error || 'Error while executing POST for route ' + path); // }); } // public postData(path: string, body: Object = {}) { // debugger; // return this.http.post( // this.API_ENDPOINT + path, // body); // } public post(path, data) { return this.http.post(this.API_ENDPOINT + path, data, {headers: this.postheaders}) .pipe(map((response: any) => response)) // .map(this.extractData) // .catch(error => { // return this.handleError(error || 'Error while executing POST for route ' + path); // }); } public put(path, data) { return this.http.put(this.API_ENDPOINT + path, data,{headers: this.headers}).pipe(map((response: any) => response)) // .catch(error => { // return this.handleError(error || 'Error while executing POST for route ' + path); // }); } protected async postDataAsync(path, data): Promise { try { const res$ = await this.http.post(this.API_ENDPOINT + path, data, {headers: this.postheaders}); const res = await lastValueFrom(res$); return res; } catch (err) { return this.handleError(err || 'Error while executing POST for route ' + path); } } protected async getAsync(path: string): Promise { try { const res$ = await this.http.get(this.API_ENDPOINT + path); const res = await lastValueFrom(res$); return res; } catch (err) { return this.handleError(err || 'Error while executing POST for route ' + path); } } protected async getRMAsync(path: string,data:any): Promise { try { const res$ = await this.http.post(this.RM_ENDPOINT + path, data,{headers: this.postheaders}); // this.hideLoadingPanel(isNoLoadingPanel); const res = await lastValueFrom(res$); return res; } catch (err) { return this.handleError(err || 'Error while executing POST for route ' + path); } } protected async postCommonApi(path: string, data: any): Promise { try { const res$ = await this.http.post(this.config.commonApiServiceUrl + path, data, { headers: this.postheaders }); const res = await lastValueFrom(res$); return res; } catch (err) { return this.handleError(err || 'Error while executing POST for route ' + path); } } private handleError(error: any) { let data; try { data = error.error || error; } catch (e) { data = {error: null}; } return throwError({status: error.status, data}); } private extractData(res: any) { try { console.log(res); return res || {}; } catch (e) { return res; } } // Debug method to check headers specifically for ValidateUid public debugValidateUidHeaders() { console.log('=== ValidateUid Headers Debug ==='); console.log('this.postheaders:', this.postheaders); console.log('this.API_ENDPOINT:', this.API_ENDPOINT); console.log('Content-Type in postheaders:', this.postheaders.get('Content-Type')); console.log('=== End ValidateUid Headers Debug ==='); } // Special method for ValidateUid with forced JSON handling public postDataForValidateUid(path: string, data: any) { if (!path.includes('ValidateUid')) { console.warn('postDataForValidateUid should only be used for ValidateUid endpoints'); return this.postData(path, data); } console.log('=== ValidateUid Special Request ==='); console.log('Using special ValidateUid method with forced JSON handling'); // Create headers specifically for ValidateUid const validateUidHeaders = new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Cache-Control': 'no-cache' }); console.log('ValidateUid headers:', validateUidHeaders); console.log('ValidateUid data:', data); console.log('ValidateUid full URL:', this.API_ENDPOINT + path); // Ensure valid JSON when body is a raw string const jsonBody = typeof data === 'string' ? JSON.stringify(data) : data; return this.http.post(this.API_ENDPOINT + path, jsonBody, { headers: validateUidHeaders, responseType: 'json' // Force JSON response type }).pipe(map((response: any) => { console.log('=== ValidateUid Special Response ==='); console.log('Raw response:', response); console.log('Response type:', typeof response); // Ensure we return parsed JSON if (typeof response === 'string') { try { const parsed = JSON.parse(response); console.log('Parsed response:', parsed); return parsed; } catch (e) { console.error('Failed to parse ValidateUid response:', e); return response; } } return response; })); } // Try multiple content-types/payload shapes for legacy ValidateUid endpoints public async postValidateUidWithFallbacks(path: string, uid: string): Promise { const fullUrl = this.API_ENDPOINT + path; // 1) text/plain raw body try { const res$ = this.http.post(fullUrl, uid, { headers: new HttpHeaders({ 'Content-Type': 'text/plain' }), responseType: 'json' }); return await lastValueFrom(res$); } catch (err: any) { if (err?.status !== 400) throw err; } // 2) JSON object with UserUid key try { const res$ = this.http.post(fullUrl, { UserUid: uid }, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), responseType: 'json' }); return await lastValueFrom(res$); } catch (err: any) { if (err?.status !== 400) throw err; } // 3) application/x-www-form-urlencoded try { const body = `UserUid=${encodeURIComponent(uid)}`; const res$ = this.http.post(fullUrl, body, { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }), responseType: 'json' }); return await lastValueFrom(res$); } catch (err) { throw err; } } }