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);
});
3
  • Can you show your backend code and what is the response you are getting back from there, and structure of the response object? Commented Mar 10, 2019 at 15:58
  • i already edit my code, check it out Commented Mar 10, 2019 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)) stackoverflow.com/q/44292270/4834833 Commented Mar 14, 2019 at 3:41

1 Answer 1

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"');
      });
    }

  }

Sign up to request clarification or add additional context in comments.

13 Comments

loginstudent(data) { const postHttpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), observe: 'response' }; return this.http.post('localhost:8080' + 'login', data, postHttpOptions) .pipe(map(response => { return response; })); }
ill let u know later
Any idea why got error here imgur.com/gb0XUls on postHttpOptions?
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.
Just change if condition to if (result.status === '202'). It give desired output.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.