В файле app.service.ts
import { Injectable } from '@angular/core';
import { Http,Response,Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class UserActionsService {
user_action_url: string;
data : any={'success':'',error:''};
constructor(private _http: Http) { }
post_method() {
var headers = new Headers;
headers.append('Content-Type','application/json; charset=utf-8');
return this._http.post(this.user_action_url,this.data,{headers:headers}).map(res=>res);
}
}
В файле login.component.ts
import { Component, OnInit } from '@angular/core';
import { AppService } from './app.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
User : Logindetails;
user_data: any;
token: string;
constructor( private useraction_service : AppService,) {
}
ngOnInit() {
this.User = {
username : "",
email : "",
password : ""
}
}
loginform(User) {
this.useraction_service.user_action_url = 'http://localhost:3000/login/';
this.useraction_service.data = this.User;
this.useraction_service.post_method().subscribe(res => {
this.user_data = res.json();
if(this.user_data.status == 2 ) {
console.log('wrong credentials');
} else {
console.log('logged in successfully');
}
}
},(error: any) => {
console.log(error);
}
);
}
}
interface Logindetails {
email : String;
password : String;
}
app.component.html
<form class="example-form" name="loginform" #login="ngForm" (ngSubmit)="loginform(User)" novalidate>
<mat-form-field>
<input matInput name="emailid" [(ngModel)]="User.email" [(ngModel)]="User.username" #email="ngModel" placeholder="Enter your username or Email ID" required>
</mat-form-field>
<mat-form-field>
<input matInput name="password" [(ngModel)]="User.password" #email="ngModel" placeholder="Enter your Password" required>
</mat-form-field>
<div class="register_btn">
<button type="submit" mat-raised-button color="accent" [disabled]="!login.form.valid">Login</button>
</div>
</form>