Discrepancy between code, output from ng build, and how the browser is

I am in the process of developing an Angular 13 library that includes two services and a group of models. These services consist of an authentication service and a client service. However, after building the library, I noticed some global variables missing, and the browser interprets it incorrectly, causing further issues which will be better explained through examples.

Below is the code for the authentication service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

export interface IAuthenticate {
    Token: string,
    TwoFactor: boolean,
    UserId: string,
    MaxRetry: number
}

@Injectable({
  providedIn: 'root'
})
export class Auth {
  constructor(private http:HttpClient) { }
  
  public authenticate(username:string, password:string, url:string):Observable<IAuthenticate> {
    const URL = url+'/Auth';

    const httpOptions = {
      headers: new HttpHeaders({ Authorization: 'Basic ' + btoa(username + ':' + password) })
    }
    return this.http.get<IAuthenticate>(URL, httpOptions)
  }

}

Here is the code for the client service:

import { Injectable } from '@angular/core' 
import { HttpClient, HttpHeaders } from '@angular/common/http' 
import { Observable } from 'rxjs' 

@Injectable({
  providedIn: 'root'
})
export class DatalexClient { 
    constructor(private http:HttpClient) { } 

    token!: string; 
    webURL!: string; 

    public InitializeClient(token: string, webURL: string, callback: () => any) {
        this.token = token;
        this.webURL = webURL;
        callback()
    }

    public GetAccounts(): Observable<any[]> 
    { 
        const URL = this.webURL + '/GetAccountss'; 
        const body = { 
            'token': this.token, 
        }; 
        const httpOptions = { 
            headers: new HttpHeaders({'content-type': 'application/json'}) 
        } 
        return this.http.post<any[]>(URL, body, httpOptions); 
    }  

}

The idea behind these services is to first authenticate the user and then initialize the client by setting the token and web URL.

This is how I planned to use it in my project:

// inside component class

this.dlxAuth.authenticate(this.username, this.password, "url").subscribe({
next: (r) => this.client.InitializeClient(r.token, "url", this.callback),
error: console.error.bind(this)
})

callback(): any {
console.log("initialized")
// initialization code
}

However, when I tried to call "InitializeClient," I encountered an error stating that "ERROR TypeError: this.dlxClient.InitializeClient is not a function." This was perplexing as I verified that "InitializeClient" existed in all the relevant files in the library project output, yet it was missing when inspecting it in Chrome DevTools within node_modules -> mylib client.mjs.

I managed to work around this issue by directly setting the token and web URL:

// inside component class

this.auth.authenticate(this.username, this.password, url).subscribe({
next: (r) => {
// this.client.InitializeClient(r.Token, url, this.init);
this.client.token = r.Token;
this.client.webURL = url;
this.init();
},
error: console.error.bind(this)
})

This workaround seemed effective as checking "this.client" via console.log showed the token and URL present.

With a valid token and URL set in the client service, I attempted to fetch accounts in a component:

Here is the implementation:

this.client.GetAccounts().subscribe({
next: console.log.bind(this),
error: console.error.bind(this)
});

A second problem arose at this point. The HTTP request failed because the URL passed to the function was "undefined." Upon investigating the source in the browser, it became apparent that it was trying to use "this.auth.url," which doesn't exist anywhere in my code, including the compiled or interpreted code in the browser.

Screenshots from browser source showing the unexpected behavior:

https://i.sstatic.net/pdr7n.png

https://i.sstatic.net/gguHQ.png

If anyone can shed light on why this is happening, I would greatly appreciate it.

Answer №1

Halting and then relaunching "NG SERVE" resolved my issue, it appears that the bundler failed to incorporate the recently updated files without a restart.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue when retrieving the value from a template-driven Angular form

Encountering an issue in the register function regarding storing the form control value. When using "let firstname", "let lastname", and "let email", I am receiving the error [tslint] Identifier 'firstName' is never reassigned; use 'const&a ...

How can we ensure that material-ui fields render properly following a reset call in react-hook-form?

I am currently working on a page for editing, but I have encountered an issue with react MUI not rendering text fields properly after updating my form data using the reset method from react-hook-form. This is the current appearance of the form: https://i ...

Angular - Show a table of items from a given list

I recently started using Angular and I'm facing a challenge in displaying multiple tables based on a list of values. Each rule refNo should have its own separate rule conditions table displayed sequentially. Currently, all the tables are showing the s ...

Angular Space-Friendly Table

After attempting to code the sample in Angular, I realized it wasn't what I was looking for. <table> <th >Number</th> <th >Merchant Name</th> ...

Error in Mongoose Schema Configuration Detected in NestJS App

I'm currently developing an e-commerce application using NestJS and MongoDB with Mongoose. I've been facing an issue while trying to implement a user's shopping cart in the application. The error message I keep encountering is as follows: ...

Initiate npm start with CORS enabled

Currently, I am developing a small application using Angular2. Following the instructions provided in the 5min. Quickstart Guide, I used npm to install necessary modules and initiate a lite-server. However, my ultimate goal is to integrate this app into ...

When I run ng build, an error code ".form-floating>~label" pops up

After running the command "ng build" in my Angular app, I encountered the following output: ✔ Browser application bundle generation complete. ✔ Copying assets complete. ⠋ Generating index html...4 rules skipped due to selector errors: .form-floatin ...

What is the method for placing a title in the initial column with the help of v-simple-table from Vuetify.js?

I am interested in using the v-simple-table UI component from Vuetify.js to create a table similar to the one shown below. https://i.sstatic.net/QNdpJ.png After creating the code in codesandbox and previewing the output, I noticed that the title is not a ...

Dealing with throwing Exceptions in jest: A guide for developers

I have developed a method that throws an exception when the provided password does not match a regex pattern. I attempted to handle this in Jest. it('Should prevent insertion of a new user if the password doesn't match the regex', async () ...

Incorporate an external JS file (File A) that is dependent on another JS file (File B) into a TypeScript file within the context of Angular 4

Working on an Angular 4 project, I recently installed two external JS libraries using npm. They are now in the node_modules folder and usable in another TS file within my project. The issue arises because import B requires import A, preventing me from effe ...

The Typescript code manages to compile despite the potential issue with the type

In my coding example, I have created a Try type to represent results. The Failure type encompasses all possible failures, with 'Incorrect' not being one of them. Despite this, I have included Incorrect as a potential Failure. type Attempt<T, ...

Having trouble with Angular Ng2-file-Upload's Upload.all() method not successfully sending files to the API

Dealing with the challenge of uploading files in mp4 and jpg formats, I have set up 2 separate instances of FileUploader with custom validation. Upon clicking the upload button, I attempt to merge the files from both instances into a single FileUploader ...

Leverage advanced type deduction in Key Remapping

I'm puzzled by this code snippet: type Foo<T extends string> = [T] extends [infer Y] ? Y : never // works fine type Test_2<T extends Array<string>> = { [P in T[number] as Foo<"foo">]: undefined } // no issues type ...

Found in the NgModule.imports section of the AppModule, yet was unable to be identified as an NgModule class in Angular version 12.2.9

Just set up a fresh angular 12 application and installed version 12 of @angular/material. Now I'm trying to implement it by adding this basic element: <mat-drawer-container></mat-drawer-container> However, all I see in the browser is a wh ...

Can you identify the specific function type passed through props?

interface IProps { handleCloseModal: React.MouseEventHandler<HTMLButtonElement> returnFunction: () => void; } export default function Modal({ children, returnFunction, handleCloseModal, }: React.PropsWithChildren<IProps>) { cons ...

Can you explain the process for accessing a parent function in Angular?

I have a form component that inserts data into a database upon submission, and I need to update the displayed data in another component once it changes in the database. I attempted using ViewChild to invoke the necessary functions, but encountered issues w ...

Can template literal types be utilized to verify if one numeric value is greater than another?

I am attempting to define the Record for migration functions, which use the direction of the migration as the key: v${number}-v${number}, Considering that these migrations are all UP, they need to be validated as v${first-number}-v${first-number + 1} and ...

Is there a way to enhance a pre-existing component in Angular?

Trying to integrate an Angular component and wanting to implement a unique template. By referencing the documentation, it is possible to customize the menuComponent by utilizing the built-in TextInputAutocompleteMenuComponent component to apply a custom t ...

Add the item to the array and then use the *ngFor directive to iterate

Whenever the addRoom button is clicked, I want to add an object to an array. The problem is that the data in my array keeps getting repeated. Please excuse any language errors in my explanation. Feel free to ask me for clarification in the comments below. ...

Error when running end-to-end tests in Angular CLI using the ng e2e

Recently, I created a new Angular 4 project using the Angular CLI. Upon running ng e2e, the sample end-to-end test worked flawlessly. However, when I later added a subfolder named services in the app folder and generated a service within it, the ng e2e com ...