Home > Software engineering >  Angular 14 Log to a website with a post and a header
Angular 14 Log to a website with a post and a header

Time:12-28

I am trying since a week to create a service to be able to connect to a website and get information on this website. (Like the list of machines...).

I would like to do something like that but in Ts with Angular and with the HTTP client of Angular.

What i am trying to do :

var axios = require('axios').default

var email = '[email protected]'
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 have right now :

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 >
  <div >
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
      <div >
        <label>Email</label>
        <input  type="text" formControlName="email" required>
      </div>
      <div >
        <label>Password</label>
      <input  type="password" formControlName="password" required>
      </div>
      <br>
      <div >
        <button  type="submit">Submit</button>
      </div>
    </form>
  </div>
</div>

I did try many others things too but i always get to the same point it isn't working ^^. Right now i always have the error ERROR TypeError: this.form.get is not a function.

CodePudding user response:

form supposed to be type of FormGroup, so replace:

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

with:

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

CodePudding user response:

Thanks a lot for you answer ! :)

I did change the code to :

form = new FormGroup({
  email: new FormControl('', {nonNullable: true}),
  password: new FormControl('', {nonNullable: 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 send the login to the website. But i have the error 405: Method not allowed. I think that i am not using properly the header and the token.

  • Related