When employing HTTP GET within Angular 2, it prompts the retrieval of a response in my subsequent HTTP POST request for

Greetings! I am relatively new to Angular 2 and I am encountering some unexpected HTTP behavior.

Below is my login method used to send an HTTP POST request to my backend server and retrieve a token. It is functioning properly.

public login(username, password) {

const headers = new Headers({
  'Content-Type': 'application/x-www-form-urlencoded',
  'Authorization': 'Basic ' + btoa('live-test:')
});

const requestOptions = new RequestOptions({ headers });

const urlSearchParamsLogin = new URLSearchParams();
urlSearchParamsLogin.append('grant_type', 'password');
urlSearchParamsLogin.append('client_id', 'live-test');
urlSearchParamsLogin.append('username', username);
urlSearchParamsLogin.append('password', password);

const paramsLogin = urlSearchParamsLogin.toString();

this.http.post(this.urlAuth, paramsLogin, requestOptions)
  .map(response => response.json().access_token)
  .subscribe(
    response => {
      localStorage.setItem('token', response);
      alert(localStorage.getItem('token'));
    },
    error => {
      console.log(error.text());
    }
  );
}

Now, here is my checkToken method:

public checkToken() {

const token = localStorage.getItem('token');

const headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Accept', 'application/json');

const urlSearchParamsCheckToken = new URLSearchParams();
urlSearchParamsCheckToken.append('token', token);

const paramsCheckToken = urlSearchParamsCheckToken.toString();

const options = new RequestOptions({ headers: headers , params: 
paramsCheckToken});

this.http.get('http://localhost:8082/cq-webapp/oauth/check_token', options )
  .map(response => response.json().user_name)
  .subscribe(
    response => {
      alert(response);
    },
    error => {
      console.log(error.text());
    }
  );
 }

}

While the checkToken method is functioning correctly, it seems that after receiving the HTTP response from my Java backend, the login method above is receiving another response with the token. Why is this happening? Is it due to asynchronous behavior in Angular 2, and is there a way to prevent this?

I believe this issue is specific to Angular 2 Typescript rather than my Spring backend, as Postman does not exhibit the same behavior when making a checkToken HTTP GET request.

Any insights or suggestions would be greatly appreciated.

****Update: I have identified the fix. I am still curious as to why the previous HTML structure was causing the login method to trigger upon clicking the checkToken button.

Here is the original HTML structure:

<div>
    <h1>Login</h1>
    <form role="form" (submit)="login(username.value, password.value)">
    <div class="form-group">
        <label for="username">Username</label>
        <input type="text" #username class="form-control" id="username" 
        placeholder="Username">
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <input type="password" #password class="form-control" id="password" 
        placeholder="Password">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>

    <button (click)="checkToken()" >Check Token</button>
    </form>
</div>

Here is the corrected HTML structure:

<div>
<h1>Login</h1>
<form role="form">
<div class="form-group">
    <label for="username">Username</label>
    <input type="text" #username class="form-control" id="username" 
    placeholder="Username">
 </div>
 <div class="form-group">
    <label for="password">Password</label>
    <input type="password" #password class="form-control" id="password" 
    placeholder="Password">
  </div>
  <button (click)="login(username.value, password.value)">Submit</button>

  <button (click)="checkToken()" >Check Token</button>
</form>
</div>

Answer №1

The reason for this issue is the absence of the type attribute on your checkToken button. If the type attribute is not specified, the default value is submit (except in IE, so it is recommended to always specify it).

As a result, when you clicked the button, the form was submitted, triggering both the checkToken (click) and login (submit) events.

For more information, you can refer to: https://www.w3.org/TR/html401/interact/forms.html#h-17.5

type = submit|button|reset [CI]

This attribute defines the type of the button. Possible values:

  • submit: Creates a submit button. This is the default value.
  • reset: Creates a reset button.
  • button: Creates a push button.

Answer №2

Consider using objects instead of URLSearchParams

let userData ={
    grant_type: 'password',
    client_id: 'live-test',
    username: username,
    password: 'password'
}

this.http.post(this.urlAuth, userData, requestOptions);

Remember to subscribe to the response within the service to avoid long waiting times in the component.

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

Updating Mysql through REST API/JWT using PUT method is not possible

I have been attempting to send an update request using Jwt (Tokens) and Node.Js with a backend in mysql. While Postman confirms that the record has been successfully updated, I am unable to locate where the actual update occurred. No changes seem to be ref ...

List component in Angular not refreshing after sorting the array in the service

Currently, I am delving into the realm of Angular (version 5+) to enhance my skills by working on a small project. The project involves setting up basic routing functionalities to showcase the ContactList component upon selecting a navigation tab. Addition ...

Exploring the capabilities of multiple router-outlets and submodules within Angular 5

Despite my extensive review of the documentation and other questions, I am still struggling to find a suitable solution for my project. I decided to steer clear of the named router-outlets option as it results in a less clean URL. It seems that many of the ...

Guide on creating a typed object variable in Typescript

In my Typescript code, I have an interface called Employees: export interface Employees { [employeeId: string]: { name: string gender: Gender } } I am trying to declare a variable employees that is of type Employees. Here are the attempts I h ...

Employing AJAX, execute a synchronous function asynchronously (Javascript)

Here's a code snippet for the sync function. I've been calling it inside an Ajax, but apparently it's deprecated because it's synchronous. Is there any way to make it run as if it were asynchronous? Or is there a way to convert it into ...

When two-dimensional arrays meet destructuring, it results in a type error

Can anyone clarify TypeScript behavior in this scenario? JavaScript const test1 = [ ['a', 'b'], ['c', 'd'], ]; const test2 = [ ...[ ['a', 'b'], ['c', ' ...

What is the best way to identify errors in an express listen callback function?

My current code is set up to verify if there was an error while initiating Express: express() .listen(port, (err: Error) => { if (err) { console.error(err); return; } console.log(`Express started`); ...

Guide to activating data transfer object validators in NEST JS

I have recently started using NEST JS and I am currently working on implementing validators in DTO's. This is what my code looks like: // /blog-backend/src/blog/dto/create-post.dto.ts import { IsEmail, IsNotEmpty, IsDefined } from 'class-validat ...

Deactivate the FormGroup by implementing Validators

In my form, I have a checkbox group named formArray within my checkboxForm. The task at hand is to disable the submit button if none of the checkboxes are checked. To achieve this, I created a custom validator for my checkboxForm and here is my approach: ...

Only apply patches to untouched values

Looking for a way to patch only the pristine properties of my reactive form in Angular. Received updates from a websocket service regarding user data, and want to update the form based on the payload without changing dirty properties. Below is the code s ...

Showing particular URL text upon opening a new window using JavaScript

I've encountered an intriguing scenario. In my application, there's a feature that triggers a new window/tab to open when a button is clicked. Upon opening, a predefined HTML page is shown to the user with a specific URL set. I'm curious abo ...

Converting an HTMLElement to a Node in Typescript

Is there a method to transform an HTMLElement into a Node element? As indicated in this response (), an Element is one specific type of node... However, I am unable to locate a process for conversion. I specifically require a Node element in order to inp ...

utilize Angular's interface-calling capabilities

In the backend, I have an interface structured like this: export interface DailyGoal extends Base { date: Date; percentage: number; } Now, I am attempting to reference that in my component.ts file import { DailyGoal } from '../../interfaces' ...

Is there a way to incorporate my getter into a computed property?

My Vuex Store is built using Vuex module decorators and I am facing an issue with using a getter for a computed property. Here is my code: @Module export default class WorkoutModule extends VuexModule { _workout: Workout; @Mutation startWork ...

An issue has occurred: Unable to access the 'seatsavailable' property of an undefined object

Currently, I am immersed in a project involving Angular 6 and utilizing the @Input and @Output decorators. In this scenario, I have the Bookride Component functioning as the parent component with RideDetails serving as the child component. Successfully tra ...

When using TypeScript, how can I effectively utilize the Component property obtained from connect()?

Software Development Environment TypeScript 2.8 React 16 Redux Foo.tsx interface IFooProps{ userId:number } class Foo extends Component<IFooProps>{ render(){ return <p>foo...</p> } } const mapStateToProps = (state: I ...

"Learn the trick to selecting a material checkbox by simply clicking on the table cell (td)

Is there a way to have a checkbox automatically checked when clicking on a table cell? I attempted to use a reference variable, but encountered an error. Error message: DetailComponent.html:97 ERROR TypeError: jit_nodeValue_15(...).click is not a func ...

Using the record key as the index for the function argument type

In my current setup, I have : const useFormTransform = <T>( formValues: T, transform: Partial<Record<keyof T, (value: T[keyof T]) => any>>, ) => ... This is how it's used : type Line = { id?: string; fromQuantity: number } ...

What sets apart WordPress REST API from WP JSON API?

I'm currently developing an authentication feature for my app using API. I'm having difficulty deciding between utilizing the WordPress REST API or the WordPress JSON API. Reading through this Q&A thread, it suggests that I should opt for the ...

Injecting data into mat-dialog-actions in Angular - how can it be done?

I have a question regarding passing data to a method in Angular. Below is the code snippet: Is there a way to pass data into addNpi() similar to how editNpi(data) is done below? Your help is appreciated. Thank you! <mat-dialog-content> <ip-dat ...