0

I want to make a login page where I need to validate the student id and password to be matched from the database. I have the back-end API that sends validate the student account and sends response status when they are success or failed.

Here is my LoginComponent.ts

export class LoginComponent {

studentForm: FormGroup;

constructor(
private fb: FormBuilder,
private crudService: CrudService,
private router: Router) {
  this.studentForm = this.fb.group({
    id: ['', Validators.compose([Validators.required])],
    password: ['', Validators.compose([Validators.required])]
  });
}
// This are the example for inserting data into database
saveStudentDetails(values) {
  const studentData = new FormData();

  studentData.append('id', values.id);
  studentData.append('password', values.password);
  this.crudService.loginstudent(studentData).subscribe(result => {
    if (this.crudService.getData) {
    this.router.navigate(['address']); alert  ('"success"'); return; }
  });
}
}

// MY service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

// Base api url
public url = 'http://localhost:8080/';
headerProperty: string;

constructor(private http: HttpClient) { }

createUser(data) {
  return this.http.post(this.url + 'todo', data);
}

createAddress(data) {
  return this.http.post(this.url + 'address', data);
}

}

Ignore the saveStudentDetails, it just for testing purpose and my question is how can I make a validation base on response status from API and make it go to next page if the API send a success status.

// This is my backend api using slim framework

$app->post('/login', function (Request $request, Response $response, array $args) {

$input = $request->getParsedBody();
$sql = "SELECT * FROM users WHERE id= :id";
$sth = $this->db->prepare($sql);
$sth->bindParam("id", $input['id']);
$sth->execute();
$user = $sth->fetchObject();

// verify id.
if(!$user) {
    return $this->response->withJson(['error' => true, 'message' => 'No id found'], 404);  
}
// Compare the input password and the password from database for a validation
if (strcmp($input['password'],$user->password) == 1 ) {
    return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.'], 404);  
}

    return $this->response->withJson($input,202);
});
Dale K
  • 25,246
  • 15
  • 42
  • 71
Dory
  • 95
  • 4
  • 19
  • Can you show your backend code and what is the response you are getting back from there, and structure of the response object? – Ravi Shankar Bharti Mar 10 '19 at 15:58
  • i already edit my code, check it out – Dory Mar 10 '19 at 16:11
  • Same as, in this post write angular http request like this.http.get(url, {observe: 'response'}) .subscribe(resp => console.log(resp.headers)) https://stackoverflow.com/q/44292270/4834833 – mukund patel Mar 14 '19 at 03:41

1 Answers1

3

You should pass one more parameter to POST method as follows:


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

postHttpOptions['observe'] = 'response';

return this.http.post('http://localhost:8080/'+ api_end_point, data, postHttpOptions)
.pipe(map(response => {
       return response;
  }));

As you can see, I have added observe: 'response', which returns the full response with response headers.

Now you have access to response headers. You can do this:

this.crudService.loginstudent(studentData).subscribe(result => {
  if (result.status === '202') {
    this.router.navigate(['address']); 
    alert('"success"'); 
    return; 
  }
});

Update

Use this function to send values to the API.


    saveStudentDetails(values) {
      const studentData = {};

      studentData['id'] =  values.id;
      studentData['password'] =  values.password;
      this.crudService.loginstudent(studentData).subscribe(result => {
        this.student = result;
        console.log('status code ->' + result.status);
        this.router.navigate(['/address']);
      },
        err => {
          console.log('status code ->' + err.status);
          alert('"error"');
      });
    }

  }

Dory
  • 95
  • 4
  • 19
Todarmal
  • 306
  • 1
  • 12
  • loginstudent(data) { const postHttpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), observe: 'response' }; return this.http.post('http://localhost:8080/' + 'login', data, postHttpOptions) .pipe(map(response => { return response; })); } – Dory Mar 10 '19 at 17:12
  • ill let u know later – Dory Mar 10 '19 at 17:24
  • Any idea why got error here https://imgur.com/gb0XUls on postHttpOptions? – Dory Mar 11 '19 at 09:30
  • Sorry for the late reply. But I have updated the answer a little bit. Please check it out. It should solve this error you are getting. – Todarmal Mar 13 '19 at 10:46
  • Just change `if condition` to `if (result.status === '202')`. It give desired output. – Todarmal Mar 13 '19 at 12:56
  • still the same error but now it is on the status, hmm something must be wrong here. – Dory Mar 13 '19 at 13:05
  • Use `result['status']` and you will see the status now – Todarmal Mar 13 '19 at 13:08
  • yeah its working now but i cannt login into. I have tried many others solution but when test the api on postman its working but when trying to use angular its return error 404. It must have a logic error in my logincomponent, do you have any idea about it? – Dory Mar 13 '19 at 13:18
  • Can you create this scenario over stackblitz.com so that I can have a look on it. – Todarmal Mar 13 '19 at 13:35
  • https://stackblitz.com/edit/angular-zznr1g ignore the interface, its on my logincomponent. Sorry my coding is a little bit messed up – Dory Mar 13 '19 at 13:57
  • i.stack.imgur.com/hfvU3.png this is the error, when i test my backend in postman its working but when using angular its say no id found which my first if else statement from backend, you can refer my backend above – Dory Mar 14 '19 at 03:03
  • Thank you very much sir, its working already but its look like the if statement need to be changed because it does not read the result['status'] === '200' so i already edited you answer. Nice to meet you sir. Have a nice day – Dory Mar 14 '19 at 04:16
  • My pleasure! Have a great day :) – Todarmal Mar 14 '19 at 04:20