What causes the generation of an outdated object when utilizing the let and new keywords to create a new object within a service function?

Hey there, looking for a basic auth authentication service in angular2?

Here's the issue I'm facing: When a user logs in for the first time, everything works smoothly. However, if they try to log in with a different account for the second time, I notice that there are two basic auth strings in the request headers. It looks something like this: "Authorization:Basic YWRtaW46YWJjMTIz,Basic RMcasd9WJjMXoPj".

Let me show you the code snippet:

@Injectable()
export class AuthenticationService {
private url: string = 'http://localhost:8080/api/test';
private username: string;
private password: string;
private authenticationStatus: boolean = false;

constructor(private http: Http) { }

authentication(username: string, password: string): Promise<boolean> {

    let headers = new Headers(); // <== previous headers object with old Authorization string get back from grave.
    console.log(headers);  

    headers.append("Authorization", "Basic " + btoa(username + ":" + password));
    headers.append("Content-Type","application/json;charset=utf-8");

    return this.http.get(this.url, { headers: headers })
        .toPromise()
        .then(response => { ...

This is my initial attempt at an Angular/Typescript app. I'm puzzled by not getting a fresh object when using both let and new here. Could it be due to the fact that headersString within the header class is static? I've delved into the Angular headers class API documentation but haven't managed to resolve it yet. I even tried calling headers.delete("Authorization"); immediately after let headers = new Headers();, but the old Authorization header persists.

Answer №1

I'm feeling puzzled because I expected a completely new object when using both let and new in this scenario.

When you print out an object, what is actually logged is the reference to that object.

For instance:

let x = {};
console.log(foo);
x.foo = 'foo';

If you check the content of x on your console after making changes to it, you will see the updated information:

https://i.sstatic.net/9T7hx.png

In summary, your code is accurate. However, keep in mind that appearances in the console can be deceptive.

On another note: It's possible that you are performing actions not illustrated in the provided code snippet.

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

Use Node.js with Selenium and WebdriverIO to simulate the ENTER keypress action on

I have put in a lot of effort trying to find the solution before resorting to asking this question, but unfortunately I have not been successful. All I need to know is how to send special characters (such as the enter key and backspace) with Node.js using ...

AngularJS $http.get request not working as expected

Hi there, I'm currently facing an issue with retrieving data from a webpage for use on my own website. I'm working with AngularJS and attempting to fetch data from . When checking my page in Chrome, I encountered the following error: Refere ...

What might be causing the ng-model in this plunkr to not update as expected?

I recently customized a ui-select plunkr to suit my specific needs. I've noticed that the ng-model is not updating as expected, but interestingly, clicking the button to update the model results in the ui-select getting updated. Any guidance on resol ...

Error encountered in Ubuntu while attempting to run a Python script within a Node.js/Express application: spawn EACCES

Recently, I set up a node.js server to run a python script using the python-shell . However, after migrating from Windows to Ubuntu, an EACCES error has been persistently popping up. Despite my attempts to adjust permissions and troubleshoot, I haven' ...

Unlocking the power of asynchronous methods within the useEffect() hook

When attempting to fetch an API within a useEffect(), I encountered the following error: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. Here is the code snippet that caused the error: -API being fetched: ex ...

Refreshing a section of a webpage using AJAX and PHP

After creating a RESTful API in PHP, I can easily register information by accessing the address . This registration process involves sending a POST request. Below is an overview of my method: File: api.php <?php /* File: api.php */ private function ...

What is the correct method to choose an element in jQuery based on the function's id parameter

I'm having trouble deleting an item in my to-do list app. deleteToDoItem: function(id) { $(id).remove(); console.log(id); }, Here is the function that calls deleteToDoItem: function deleteItem(event) { var itemID, splitID, t ...

Looking for the properties of the ServerResponse object in node.js - where can I locate them?

Currently, I've been diving into the book Node.js In Action. Chapter 9 introduces a message module with a function that has left me puzzled about the 'this' object when calling res.message. To gain clarity, I decided to print out the name of ...

Ways to incorporate NPM packages into your browser projects using TypeScript

This is the current setup: index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <script src="../node_modules/systemjs/dist/system.js"></script> <script src="../node_modules/lodash/in ...

What could be causing the malfunction of the v-bind attribute?

I am in the process of developing a straight-forward To-Do List application with VueJS. <template> <div> <br/> <div id="centre"> <div id="myDIV" class="header"> <h2 style="margin:5px">M ...

Directing users to varying pages based on a particular criteria

As we continue to develop our application, we are creating various pages and need to navigate between them. Our current framework is Next.js. The issue we are facing involves the Home page: when transitioning from the Home page to another page (such as pa ...

Ways to enable Urql (typescript) to accept Vue reactive variables for queries generated using graphql-codegen

I'm currently developing a Vue project that involves using urql and graphql-codegen. When utilizing useQuery() in urql, it allows for the use of Vue reactive variables to make the query reactive and update accordingly when the variables change. The ...

Observing data within an AngularJS service

I am currently working with a service called sharedData and a controller named HostController. My goal is to have the HostController monitor the saveDataObj variable within the sharedData service, and then update the value of host.dataOut, which will be re ...

Issue encountered with sortable table in list.js

Encountering a puzzling error while implementing list.js and tabletop for a sortable table sourced from a Google Doc. The error message reads: "Uncaught TypeError: Cannot read property 'childNodes' of undefined," pinpointing the first line in lis ...

The benefits of a modular design in a React and TypeScript library

Following a tutorial on creating a library with React, Typescript, and rollup, I successfully managed to get everything working. However, as my project grows with additional features, I'm looking to have modular exports similar to what is seen in redu ...

Invoking a SOAP service method defined by a message contract in soap.js

I am currently working with a soap service that utilizes message contracts. According to the rules of message contracts, both the request and response messages must be objects. Message contracts are essential for me because they provide complete control ov ...

React Prop Local Modal Redux

Just diving into the world of React and Redux, and I'm a bit lost on how to effectively utilize both local properties and redux properties simultaneously. After trying different approaches without success, I'm reaching out for guidance. My goal i ...

Express req.files returns null when using jQuery FormData

For client side functionality, I am utilizing Bootstrap and jQuery. On the server side, my technology stack includes node.js and express. The form structure is displayed below: <form id="signupform" action=""> <h2&g ...

Unable to use document.write when extracting code from the internet

I am currently developing a game using emulatorjs and ruffle. The goal is to have it all contained in a single downloadable file that can be run locally. I attempted to create another file for auto-updating purposes, but encountered issues with some of the ...

The DataType.MultilineText field in my modal popup partial view is causing all validation to fail

I encountered a peculiar issue recently. After creating a new asp.net mvc5 application, I decided to upgrade it to asp.net mvc-5.2.2. The problem arose with the following field:- [Required] [StringLength(200)] public string Name { get; set; } When ren ...