Accessing a website with Angular 14 using a log-in feature and custom header

For the past week, I've been working on developing a service that can connect to a website and retrieve information from it, such as a list of machines.

I want to achieve this using TypeScript with Angular and utilizing Angular's HTTP client.

Here is what I am attempting to do:

var axios = require('axios').default

var email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5933363137773d363c193a363429383720773a3634">[email protected]</a>'
var password = 'MYPASSWORD'
var auth_url = 'https://thisisthewebsitelink.com/api-token-auth/'
axios.post(auth_url, { email, password }).then(ret => {
var token = ret.data.token
// Create an instance with default authorization header set
var instance = axios.create({
baseURL: 'https://thisisthewebsitelink.com/api/',
headers: { Authorization: 'TOKEN ' + token },
})
// List machines
instance.get('/machines').then(ret => console.log(ret.data))
})

What I currently have:

httpservice.service.ts


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

const auth_url = 'https://thisisthewebsitelink.com/api-token-auth' ;

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class HttpService {

  constructor(private httpClient: HttpClient) { }

  

  login(email : string, password: string): Observable<any> {
    return this.httpClient.post(
      auth_url,
      {
        email,
        password,
      },
      httpOptions
    )
  }

}

app.component.ts

import { Component } from '@angular/core';
import { HttpService } from './Service/httpservice.service'; 
import { FormGroup, FormBuilder } from "@angular/forms";
import { AppModule } from './app.module';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

form: any = {
  email: null,
  password: null
};
isSuccessful = false;
isSignUpFailed = false;
errorMessage = '';

constructor(private authService: HttpService) { }

ngOnInit(): void {
}

onSubmit(): void {
  const { email, password } = this.form;

  this.authService.login(email, password).subscribe({
    next: data => {
      console.log(data);
      this.isSuccessful = true;
      this.isSignUpFailed = false;
    },
    error: err => {
      this.errorMessage = err.error.message;
      this.isSignUpFailed = true;
    }
  });
}
}

app.component.html

<div class="row justify-content-center mt-5">
  <div class="col-md-4">
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
      <div class="form-group">
        <label>Email</label>
        <input class="form-control" type="text" formControlName="email" required>
      </div>
      <div class="form-group">
        <label>Password</label>
      <input class="form-control" type="password" formControlName="password" required>
      </div>
      <br>
      <div class="form-group">
        <button class="btn btn-primary btn-block" type="submit">Submit</button>
      </div>
    </form>
  </div>
</div>

I have tried many other approaches but keep running into the same issue where it doesn't work. Right now, I'm getting the error ERROR TypeError: this.form.get is not a function.

Answer №1

It's recommended that the form should be of type FormGroup. Therefore, update the following code snippet:

form: any = {
  email: null,
  password: null
};

to:

form = new FormGroup({
 email: new FormControl(null),
 password: new FormControl(null)
});

Answer №2

Thank you for providing your solution! :)

I have updated the code to:

form = new FormGroup({
  email: new FormControl('', {required: true}),
  password: new FormControl('', {required: true})
 });
isSuccessful = false;
isSignUpFailed = false;
errorMessage = '';

constructor(private authService: HttpService) { }

ngOnInit(): void {
}

onSubmit(): void {
  const formValue = this.form.value;

  this.authService.login(formValue.email!, formValue.password!).subscribe({
    next: data => {
      console.log(data);
      this.isSuccessful = true;
      this.isSignUpFailed = false;
    },
    error: err => {
      this.errorMessage = err.error.message;
      this.isSignUpFailed = true;
    }
  });
}
}

I am now able to successfully submit the login to the website. However, I encountered the 405 Method Not Allowed error. I suspect that there might be an issue with the headers and token usage.

EDIT: After encountering a problem with the URL (see error image), I simply added a "/" at the end of my URL link, and that resolved the issue. :)

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

The img markup results in a 406 error (Not Acceptable) when trying to serve images

I am attempting to retrieve images from Symfony. /** * @Route("/provide/image/{filename}") */ public function provideImage($filename) { $path = 'myimgdir/' . $filename; $response = new BinaryFileResponse($path); return $response ...

Arranging a list of objects in Angular 6

I am facing difficulties in sorting an array of objects The structure of the object is as follows: https://i.sstatic.net/z5UMv.png My goal is to sort the *ngFor loop based on the group_id property. component.html <ul *ngFor="let list of selectgi ...

Issue with (click) event not being detected on most elements throughout Ionic 4 webpage

BACKGROUND: After working perfectly for some time, all the click events in my Ionic app suddenly stopped functioning. I have two floating action buttons that used to trigger a JS alert popup and open a modal window, but now they are unresponsive. The onl ...

An issue with the validation service has been identified, specifically concerning the default value of null in

Using Angular 10 and Password Validator Service static password(control: AbstractControl) { // {6,100} - Check if password is between 6 and 100 characters // (?=.*[0-9]) - Ensure at least one number is present in the strin ...

Error: Unexpected character < in node_modules/angular2/ts/package.json syntax

I am currently working on developing an app with Angular 2 and have encountered an error during setup. The error message I received is: SyntaxError: /home/mts/Desktop/sampleProject/appSails/node_modules/angular2/ts/package.json: Unexpected token < at O ...

Preserve final variable state - Angular

My function looks like this: flag: boolean = false; some_function(){ var foo = some_num_value; var bar = foo; // Storing value in a separate variable if(this.flag){ v ...

Unlock the full potential of Angular lazy loaded modules by gaining access to root services

Exploring the world of Angular lazy loaded modules, I have a question about accessing a root service called AuthService within lazy loaded modules. My goal is to tap into the singleton instance present in the root injector while working with these modules. ...

Encountering difficulties trying to integrate bootstrap4-toggle into Angular 8

Recently diving into Angular, I decided to enhance my project by importing bootstrap4-toggle from the following source: in order to incorporate a stylish toggle checkbox. After running npm install and confirming the presence of the package in package.json ...

Unable to resolve error TS2532: The object may be undefined

I'm encountering an error in WebStorm with this code snippet. It's showing TS2532: Object is possibly 'undefined'. Despite installing both dotenv and @types/dotenv, the error persists. How can I resolve this issue? Check out the code b ...

Guide on toggling the visibility of two child components using *ngif in Angular 4 without losing the data

Is there a way to preserve data in my child component while using *ngIf to show and hide? I am unable to utilize the [hidden] attribute. <div id="parentcomponent"> <child1 *ngif="child1"></child1> <child2 *ngif="child2"></chi ...

Guide on showcasing subscribers in a list through api (MailChimp) with the help of AsyncTask

I have successfully displayed the list name in logcat, but I am facing challenges retrieving subscribers in a list that I created in MailChimp. Could someone guide me on the best way to achieve this using AsyncTask? Thank you in advance! public class Fe ...

Using Axios to dynamically insert a variable within the weather app's link

I am currently working on a weather application using a weather app API. While I have been able to display the weather by hardcoding the country in the link, my goal is to dynamically insert the city value from the input into the link. Unfortunately, I hav ...

Using TypeScript and Angular to remove properties from an object

My RandomValue class and WeatherForecast class are causing me some trouble. The WeatherForecast class is functioning properly, populating the table with data as expected. However, the RandomValues class/interface appears to be returning a list of objects w ...

I am encountering an issue retrieving data in React using TypeScript

Here is the code snippet I am working with: type State = { ... PromotionIDs: Number[]; autoAdjustUsage: AutoAdjustUsage[] }; const InitState: State = { ... PromotionIDs: [], autoAdjustUsage: [] }; const contracts = this.state[PointsTable ...

Is it possible to manually activate a dropdown event using pure JavaScript?

I am attempting to manually trigger a dropdown event using JavaScript. Below is the function where I am trying to achieve this. I have successfully halted the initial event that occurs and now I need to initiate a dropdown event. stopNavigationTriggerDrop ...

When using this.$refs in Vue, be mindful that the object may be undefined

After switching to TypeScript, I encountered errors in some of my code related to: Object is possibly 'undefined' The version of TypeScript being used is 3.2.1 Below is the problematic code snippet: this.$refs[`stud-copy-${index}`][0].innerHTM ...

Is it possible in Angular Typescript to map the attributes of an array to a class object or generate a new object using the elements of the array?

Here are the specifications of the tools I am currently using: Angular CLI: 10.0.6 Node: 12.18.2 Operating System: win32 x6 Angular Version: 10.0.10 My goal is to retrieve selected rows from ag-grid using a specific method. When I retrieve the row, i ...

Is there a way to ensure that @angular/core is utilizing the most up-to-date version of zone.js in its peerDependencies configuration?

This code passes the test, but there is an issue: it('should successfully retrieve data when getDownloadProgress() is called', (done: DoneFn) => { let response = { 'process': {}, 'success': 'success ...

Leveraging Multiple @Input Decorators in Ionic 3 and Angular 2

Within my Ionic 3 project, I have developed a custom component called my-component. Utilizing the angular @Input functionality, data can be passed to this component with ease. In this case, I have two inputs defined as: @Input('finder') myFinder ...

Access ViewChild and ViewContainerRef in Angular component generated dynamically

Is it possible to retrieve the ViewContainerRef from a dynamically created component? The dynamic component I have includes an ngContent element inside, which needs to be populated after creation. export class Example { @ViewChild('content', ...