No values returned in Angular HttpClient GET request subscription

Trying to set up a login feature, I decided to fetch user information using a GET request and store it in local storage. However, I am encountering an issue where the code never reaches the point where I call setItem.

AuthenticationService.ts

export class AuthenticationService {
  constructor(private http: HttpClient) {}

  login(username, password) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        Authorization: 'Basic ' + btoa('' + username + ':' + password + ''),
      }),
    };
    this.http.get('api/user/loginInfo', httpOptions).subscribe((res) => {
      localStorage.setItem('currentUser', JSON.stringify(res));
    });
  }
}

login.component.ts

export class LoginComponent implements OnInit {
  constructor(private authService: AuthenticationService) {}

  ngOnInit(): void {}

  login() {
    const username = (document.getElementById('username') as HTMLInputElement)
      .value;
    const password = (document.getElementById('password') as HTMLInputElement)
      .value;
    this.authService.login(username, password);
  }
}

Answer №1

My error turned out to be quite silly. I mistakenly invoked the method from within a Form, causing an issue. By removing the form tag in the HTML, the problem has been resolved and everything is functioning correctly now.

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

Arranging data in a table by date with "."

My current use case involves working with a table that contains dates and empty strings. Despite expecting the sorting to behave a certain way, I've encountered an issue. Normally, when sorting with strings, the empty string would typically be placed ...

Oops! An error occurred: Uncaught promise rejection - invalid link found for ProductListComponent

I am currently in the process of learning Angular and Ionic, but I am feeling a bit confused as to where my mistake is. I have looked at other questions, but I still can't seem to figure it out. Can anyone provide some assistance? Perhaps someone has ...

Show various perspectives depending on the circumstances

I am looking for a solution to display a different component if my ngFor loop returns null. <ion-select interface="popover" [ngModel]="selectedKidId"> <ion-option *ngFor="let kid of kids" [value]="kid.id">{{kid.name}}</ion-option& ...

How do I go about updating my custom element after making a REST call using @angular/elements?

Looking for some assistance with my latest creation: import { Component, ViewEncapsulation, OnInit, } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { BehaviorSubject } from 'rxjs'; @C ...

Determine the selected choice in a mat-select with multiple selections made

Can you please help me find out which option was recently selected by the user in the selectionChange event for a multi-select, like the one shown below? My goal is to detect when the user clicks on the 'All' option, and ignore that specific sel ...

Combining two objects in Typescript using the spread operator and creating a reusable type

Is there a more streamlined way to dynamically add a question mark to a variable type in TypeScript, or is the approach of rewriting the type with a question mark the best way to achieve this? I'm looking to ensure that the original variables remain r ...

Is it possible for TypeScript to define keys that are permitted to be absent but not able to be assigned the value of `undefined`?

Query Synopsis My aim is to restrict explicit values of undefined while permitting implicit undefined values. Context In the realm of JavaScript, there exists a scenario where attempting to access a nonexistent key results in undefined, similarly, access ...

Tips for Modifying the currentUrl identifier in Angular 2

I am trying to change the ID property of my currentUrl object within my component. My goal is for the ID to update and then fetch the corresponding data based on that ID. However, I keep encountering this error message: "Cannot assign to read only propert ...

What is the prescribed interface or datatype for symbol type in TypeScript with JavaScript?

I have a set of symbol values in JavaScript that I want to convert to TypeScript. // Defining object values in JavaScript const size = { Large: Symbol('large'), Medium: Symbol('medium') } What is the most efficient method to conv ...

Errors in Javascript unit testing: despite being stubbed, functions are still being activated

I have encountered issues while writing unit tests, and I am currently facing errors that I am trying to troubleshoot. The specific unit test concerns the index.ts file, which calls the features/index.ts file. To simulate the default export from features/ ...

New to TypeScript: Encounter a compilation error while launching Apollo Server and attempting to resolve a promise

Seeking assistance with starting an Apollo server in a TypeScript project utilizing Express. The code snippet for my app.ts is displayed below. Upon execution, I encounter the following error: Argument of type '(value: unknown) => void' is not ...

Supplier for a module relying on data received from the server

My current component relies on "MAT_DATE_FORMATS", but I am encountering an issue where the "useValue" needs to be retrieved from the server. Is there a way to make the provider asynchronous in this case? export const MY_FORMATS = { parse: { d ...

Assign the initial value to the first parameter of a TypeScript function by referencing the second optional parameter

In the process of developing a state manager library for React, I came up with an idea to implement a helper function that would allow users to easily set deeply nested states from outside of React using a selector. The helper function I have currently loo ...

Transferring all instructions to a subordinate element within the component

I have developed a set of custom directives specifically for <input> elements. Additionally, I have created a custom component called <app-decorated-input>. Within my application, there are numerous instances of both <app-decorated-input> ...

Loading custom Angular modules results in an error

Seems like a simple thing, but I'm struggling to figure it out on my own. I have an Angular application with the following key files: app/app.module.ts app/dashboard/dashboard.component.html app/dashboard/stats-tile/stats-tile.component.html I used ...

Unable to run 'ng serve -o', however 'ng serve' functions correctly

Encountering an issue with Angular when attempting to configure the Micro frontend Framework (module federation) for both the remote and host applications. They are not located in the same workspace. When running the remote app with "ng serve -o", an error ...

An error occurred while trying to upload the image: Undefined property 'subscribe' cannot be read

Recently, I implemented a create post function that allows users to fill in the title, content, and upload an image. However, I encountered an issue where the progress bar fills up and the image gets uploaded to Firebase successfully, but it doesn't a ...

Preserve your NativeScript/Angular ImagePicker choice or retrieve the complete file path

After choosing an image with the Image Picker, I get a content// URL content://com.android.providers.media.documents/document/image%3A139 However, when using ImageSource.fromAsset(), I receive an empty object. My main objective is to save this image as a ...

Children components are not re-rendered by React

I created a basic task manager, but I'm encountering issues when trying to manage all the data from a single point within the TaskManager component. Essentially, I have a TaskManager component that acts as the container for all the data. Within this ...

Tips for implementing a search filter in a select dropdown menu using Angular

I am attempting to enhance my select option list by including a search filter. With numerous options available, I believe that having a search function will make it easier for the user to locate their desired selection. I hope my message is clear despite ...