dimanche 28 avril 2019

Angular Login not responding - using Laravel backend

I use JWTAuth in Laravel. I developed a login page using Angular 7. Laravel 5.8 serves as the backend. I tested the api from Laravel using Post, it worked perfectly. I want the user to be redirected to Home Page after clicking the Sign in button on Login Page. The button did not redirect to anywhere

I tested the the Api from Laravel backend on Postman and it works. I also inspected the page and there is no error.

This is the flow: Laravel -> AuthenticationService(Angular)->Login(Angular)

proxy-conf.json

{
    "/api/*": {
        "target": "localhost/cloudengine-sandbox/cloudengine/public/api",
        "secure": false,
        "logLevel": "debug",
        "changeOrigin": true,
        "pathRewrite": {
            "^api": ""
        }
    }
}

package.json

"start": "ng serve --proxy-config proxy.conf.json",

authentication.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';


  export interface UserDetails {
    id: number
    name: string
    email: string
    password: string
    username: string
    exp: number
    iat: number
  }

  interface TokenResponse {
      token: string
  }

  export interface TokenPayload {
      id: number
      name: string
      email: string
      password: string
  }

  @Injectable() 
  export class AuthenticationService {
    private token: string

    constructor (private http: HttpClient, private router: Router) {}

    private saveToken(token: string): void {
        localStorage.setItem('usertoken', token)
        this.token = token
    }

    private getToken(): string {
        if (!this.token){
            this.token = localStorage.getItem('usertoken')
        }
        return this.token
    }

    public getUserDetails(): UserDetails {
        const token = this.getToken()
        let payload
        if(token) {
            payload = token.split('.')[1]
            payload = window.atob(payload)
            return JSON.parse(payload)
        }else
        {
            return null
        }
    }

    public isLoggedIn(): boolean {
        const user = this.getUserDetails()
        if(user) {
            return user.exp > Date.now() /1000
        }else{
            return false
        }
    }


    public login(user: TokenPayload): Observable<any> {
        const base = this.http.post(
            '/api/login',
            { email: user.email, password: user.email},
            {
                headers:{'Content-Type': 'application/json'}
            }
        )
        console.log(user)
        const request = base.pipe(
            map((data: TokenResponse) => {
                if(data.token){
                    this.saveToken(data.token)
                }
                return data
            })
        )
            return request
    }    

  }

login.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthenticationService, TokenPayload } from '../../services/authentication.service';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent  {

credentials: TokenPayload = {
  id: 0,
  name: '',
  email: '',
  password: ''
}

constructor(private auth: AuthenticationService, private router: Router){}

login() {
  this.auth.login(this.credentials).subscribe(
    () => {
      this.router.navigateByUrl('/home')
    },
    err => {
      console.error(err)
    }
  )
}

}

login.component.html

        <form (Submit)="login()">
            <div class="alert alert-danger" [hidden]="!error">
              
            </div>
        <div class="form-group has-feedback">
            <input type="email" name="email" class="form-control" placeholder="Enter Email e.g. emailid@email.com" [(ngModel)]="credentials.email" required>
          <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
        </div>    

        <div class="form-group has-feedback">
          <input type="password" name="password" class="form-control" placeholder="Enter Password" [(ngModel)]="credentials.password" required>
          <span class="glyphicon glyphicon-lock form-control-feedback"></span>
        </div>
        <div class="row">
          <div class="col-xs-8">
            <div class="checkbox icheck">
              <label class="">
                <div class="icheckbox_square-blue" aria-checked="false" aria-disabled="false" style="position: relative;"><input type="checkbox" style="position: absolute; top: -20%; left: -20%; display: block; width: 140%; height: 140%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"><ins class="iCheck-helper" style="position: absolute; top: -20%; left: -20%; display: block; width: 140%; height: 140%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins></div> Remember Me
              </label>
            </div>
          </div>
          <!-- /.col -->
          <div class="col-xs-4">
            <button type="submit" class="btn btn-primary btn-block btn-flat"> Sign In</button>
          </div>
          <!-- /.col -->
        </div>
      </form>

I expected that when I click the Login Submit button, it should redirect to /home, but nothing is happening. Note that I have already set home on app-routing.ts

What am I not getting right, and what do I do.

Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2IMiRNN
via IFTTT

Aucun commentaire:

Enregistrer un commentaire