How to login at angle 5?

0

I'm trying to do it with httpclient but I do not get the goal this is my code

import { Component } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {SessionStorageService} from 'ngx-webstorage';
import { Router } from '@angular/router';

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

sesion = false;
user;


constructor(public _http:HttpClient, 
public _local:SessionStorageService,
public _rutas:Router) { 
}

login(event: Event){

const url = 'http://localhost/api/public/login';


this._http.post(url,{
'username':this.user.username,
'password':this.user.password

}).subscribe(data => {

    this.user = data;
    this.sesion = true;
    this._local.store('user',data);
    this._rutas.navigate(['/home']);

 console.log('ha ido bien');

 }, error => {

  console.log('error');
  this.sesion = false;
  });

}

the api arrives by post the user and the password and returns a token if they are not in the database

the html code of the form is as follows

 <form #loginForm="ngForm" (ngSubmit)="login($event)"class="col-sm-5">
 <div class="form-group">
 <label for="username">Username</label>
 <input type="text" class="form-control" id="username"  placeholder="Enter 
 Username" [(ngModel)]="user.username" #username="ngModel">

 </div>
 <div class="form-group">
 <label for="exampleInputPassword1">Password</label>
 <input type="password" class="form-control" id="password" 
 placeholder="Password" [(ngModel)]="user.password" #password="ngModel">
 </div>

 <button type="submit" class="btn btn-primary">Submit</button>
 </form>

error

    
asked by ortiga 27.02.2018 в 19:16
source

1 answer

1

Your error is when only : user;

The quick fix:

Make two string, such as:

let username: string = "";
let password: string = "";

And in the view: ( HTML ) For user [(ngModel)]="username" and for password [(ngModel)]="password" .

Another better option

  

It is to declare the User class and use it:

Class statement:

class User{
  constructor(private username:string, private password:string){
  }
}

In the code:

let user: User;

In the HTML:

For user [(ngModel)]="user.username" and for password [(ngModel)]="user.password" .

    
answered by 27.02.2018 / 19:34
source