Ahmed EL Bohoty

Ahmed EL Bohoty

  • NA
  • 128
  • 11.4k

Problem to use fake API login with Angular

Sep 11 2018 7:39 AM

I'm new to Angular , I just write service that check login but I don't have serve side code so I found fake API to test login but I don't know why it doesn't work.

Here's the site of the fake API https://reqres.in/ you can find the login API.

enter image description here

Here's the service I wrote :-
 
  1. import { Injectable } from '@angular/core';  
  2. import { Http } from '@angular/http';  
  3. import 'rxjs/add/operator/map';  
  4.   
  5. @Injectable()  
  6. export class AuthService {  
  7.   constructor(private http: Http) {  
  8.   }  
  9.   
  10.   login(credentials) {   
  11.    return this.http.post('https://reqres.in/api/login',   
  12.       JSON.stringify(credentials)).map(response=>{  
  13.         let result = response.json();  
  14.          if (result && result.token) {  
  15.            localStorage.setItem("token", result.token) ;  
  16.            return true;  
  17.          }  
  18.          else{  
  19.            return false;  
  20.          }  
  21.       });  
  22.   }  
  23.   
  24.   
  25.   isLoggedIn() {   
  26.     return false;  
  27.   }  
  28. }  

Login Component :

  1. import { AuthService } from './../services/auth.service';  
  2. import { Component } from '@angular/core';  
  3. import { Router } from "@angular/router";  
  4.   
  5. @Component({  
  6.   selector: 'login',  
  7.   templateUrl: './login.component.html',  
  8.   styleUrls: ['./login.component.css']  
  9. })  
  10. export class LoginComponent {  
  11.   invalidLogin: boolean;   
  12.   
  13.   constructor(  
  14.     private router: Router,   
  15.     private authService: AuthService) { }  
  16.   
  17.   signIn(credentials) {  
  18.     this.authService.login(credentials)  
  19.       .subscribe(result => {   
  20.         if (result)  
  21.           this.router.navigate(['/']);  
  22.         else    
  23.           this.invalidLogin = true;   
  24.       });  
  25.   }  
  26. }  
 

Answers (6)