Angular6 backend connection












0















I made a login connection which is working find.



But this connection has been made with a local connection, in my component.



As I already connected the backend in my Service, how can I check email and password in my database?



Sorry, I'm new in Angular, and dev in general...



Thanks in advance for your help!



Component:



import { Component, NgModule, OnInit } from '@angular/core';
import { ReactiveFormsModule, FormControl, FormGroup, NgForm, FormBuilder, Validators } from '@angular/forms';
import { userService } from '../services/user.service';
import { HttpClientModule } from '@angular/common/http';
import { HttpModule } from '@angular/http';
import { UserModel } from '../models/user.model';
import { Router } from '@angular/router';

@NgModule({
imports: [
ReactiveFormsModule,
FormControl,
FormGroup,
HttpClientModule,
HttpModule
],
})

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit{
model: UserModel = {username: "ambre.naude@infogene.fr", password: "test1234"};
loginForm: FormGroup;
message: string;

loginUserData = {}

constructor(private _userService: userService,
private _userModel: UserModel,
private router: Router,
private formBuilder: FormBuilder) {}

ngOnInit(){
//connexion au backend
this._userService.setUrl();
this._userService

//connexion à l'url du site
/*this._userService.getConfiguration();*/

//pour la fonction de login
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required] });
this._userService.logout();

}
get f() { return this.loginForm.controls; }

login(){
if (this.loginForm.invalid) {
return;
}
else{
if(this.f.username.value == this.model.username && this.f.password.value == this.model.password){
console.log("Login successful");
localStorage.setItem('isLoggedIn', "true");
localStorage.setItem('token', this.f.username.value);
this.router.navigate(['/home']);
}
else{
this.message = "Veuillez vérifier vos identifiants";
}
}
}
}


Service:



import { Injectable, OnInit } from "@angular/core";
import { FormBuilder } from "@angular/forms";
import { HttpClient } from '@angular/common/http';

import { Router } from "@angular/router";
import { UserModel } from '../models/user.model';

export enum Endpoints {
login = "/login",
logout = "/LOGOUT",
etc = "/ETC"
}

@Injectable()
export class userService implements OnInit{

//pour connexion au backend
private configJson: any;
private configJsonLogin: any;
private url: string;
public href: string = "";


constructor(private http: HttpClient,
private router: Router,
private _userModel: UserModel,
private formBuilder: FormBuilder
){
}

ngOnInit(){}

async setUrl(){
//connexion au backend
this.configJson = await this.http.get('../../assets/config.json').toPromise();
this.url = this.configJson.url;
console.log(this.url);
}

logout(): void {
localStorage.setItem('isLoggedIn', "false");
localStorage.removeItem('token');
}
}


HTML:



<section class="background">

<form class="connexion" [formGroup]="loginForm" (ngSubmit)="login()" name="form" #f="ngForm">

<mat-form-field [ngClass]="{ 'has-error': submitted && f.userid.errors }">

<label for="email">Email</label>
<input matInput type="text" formControlName="username" name="email" required email />
<div *ngIf="submitted && f.username.errors">
<div *ngIf="f.username.errors.required">Vérifiez votre mail</div>
</div>

</mat-form-field>

<mat-form-field [ngClass]="{ 'has-error': submitted && f.password.errors }">

<label for="password">Password</label>
<input matInput type="password" formControlName="password" name="password" required minlength="8" />
<div *ngIf="submitted && f.password.errors">
<div *ngIf="f.password.errors.required">Vérifiez votre mot de passe</div>
</div>

</mat-form-field>

<div>
<p *ngIf="message">{{message}}</p>
<button mat-raised-button>Connexion</button><br/>
<a routerLink='motdepasse' mat-button>Mot de passe oublié?</a>
</div>

</form>
</section>









share|improve this question

























  • What exactly do you mean by how can I check email and password in my database?

    – SiddAjmera
    Nov 22 '18 at 9:48
















0















I made a login connection which is working find.



But this connection has been made with a local connection, in my component.



As I already connected the backend in my Service, how can I check email and password in my database?



Sorry, I'm new in Angular, and dev in general...



Thanks in advance for your help!



Component:



import { Component, NgModule, OnInit } from '@angular/core';
import { ReactiveFormsModule, FormControl, FormGroup, NgForm, FormBuilder, Validators } from '@angular/forms';
import { userService } from '../services/user.service';
import { HttpClientModule } from '@angular/common/http';
import { HttpModule } from '@angular/http';
import { UserModel } from '../models/user.model';
import { Router } from '@angular/router';

@NgModule({
imports: [
ReactiveFormsModule,
FormControl,
FormGroup,
HttpClientModule,
HttpModule
],
})

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit{
model: UserModel = {username: "ambre.naude@infogene.fr", password: "test1234"};
loginForm: FormGroup;
message: string;

loginUserData = {}

constructor(private _userService: userService,
private _userModel: UserModel,
private router: Router,
private formBuilder: FormBuilder) {}

ngOnInit(){
//connexion au backend
this._userService.setUrl();
this._userService

//connexion à l'url du site
/*this._userService.getConfiguration();*/

//pour la fonction de login
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required] });
this._userService.logout();

}
get f() { return this.loginForm.controls; }

login(){
if (this.loginForm.invalid) {
return;
}
else{
if(this.f.username.value == this.model.username && this.f.password.value == this.model.password){
console.log("Login successful");
localStorage.setItem('isLoggedIn', "true");
localStorage.setItem('token', this.f.username.value);
this.router.navigate(['/home']);
}
else{
this.message = "Veuillez vérifier vos identifiants";
}
}
}
}


Service:



import { Injectable, OnInit } from "@angular/core";
import { FormBuilder } from "@angular/forms";
import { HttpClient } from '@angular/common/http';

import { Router } from "@angular/router";
import { UserModel } from '../models/user.model';

export enum Endpoints {
login = "/login",
logout = "/LOGOUT",
etc = "/ETC"
}

@Injectable()
export class userService implements OnInit{

//pour connexion au backend
private configJson: any;
private configJsonLogin: any;
private url: string;
public href: string = "";


constructor(private http: HttpClient,
private router: Router,
private _userModel: UserModel,
private formBuilder: FormBuilder
){
}

ngOnInit(){}

async setUrl(){
//connexion au backend
this.configJson = await this.http.get('../../assets/config.json').toPromise();
this.url = this.configJson.url;
console.log(this.url);
}

logout(): void {
localStorage.setItem('isLoggedIn', "false");
localStorage.removeItem('token');
}
}


HTML:



<section class="background">

<form class="connexion" [formGroup]="loginForm" (ngSubmit)="login()" name="form" #f="ngForm">

<mat-form-field [ngClass]="{ 'has-error': submitted && f.userid.errors }">

<label for="email">Email</label>
<input matInput type="text" formControlName="username" name="email" required email />
<div *ngIf="submitted && f.username.errors">
<div *ngIf="f.username.errors.required">Vérifiez votre mail</div>
</div>

</mat-form-field>

<mat-form-field [ngClass]="{ 'has-error': submitted && f.password.errors }">

<label for="password">Password</label>
<input matInput type="password" formControlName="password" name="password" required minlength="8" />
<div *ngIf="submitted && f.password.errors">
<div *ngIf="f.password.errors.required">Vérifiez votre mot de passe</div>
</div>

</mat-form-field>

<div>
<p *ngIf="message">{{message}}</p>
<button mat-raised-button>Connexion</button><br/>
<a routerLink='motdepasse' mat-button>Mot de passe oublié?</a>
</div>

</form>
</section>









share|improve this question

























  • What exactly do you mean by how can I check email and password in my database?

    – SiddAjmera
    Nov 22 '18 at 9:48














0












0








0








I made a login connection which is working find.



But this connection has been made with a local connection, in my component.



As I already connected the backend in my Service, how can I check email and password in my database?



Sorry, I'm new in Angular, and dev in general...



Thanks in advance for your help!



Component:



import { Component, NgModule, OnInit } from '@angular/core';
import { ReactiveFormsModule, FormControl, FormGroup, NgForm, FormBuilder, Validators } from '@angular/forms';
import { userService } from '../services/user.service';
import { HttpClientModule } from '@angular/common/http';
import { HttpModule } from '@angular/http';
import { UserModel } from '../models/user.model';
import { Router } from '@angular/router';

@NgModule({
imports: [
ReactiveFormsModule,
FormControl,
FormGroup,
HttpClientModule,
HttpModule
],
})

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit{
model: UserModel = {username: "ambre.naude@infogene.fr", password: "test1234"};
loginForm: FormGroup;
message: string;

loginUserData = {}

constructor(private _userService: userService,
private _userModel: UserModel,
private router: Router,
private formBuilder: FormBuilder) {}

ngOnInit(){
//connexion au backend
this._userService.setUrl();
this._userService

//connexion à l'url du site
/*this._userService.getConfiguration();*/

//pour la fonction de login
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required] });
this._userService.logout();

}
get f() { return this.loginForm.controls; }

login(){
if (this.loginForm.invalid) {
return;
}
else{
if(this.f.username.value == this.model.username && this.f.password.value == this.model.password){
console.log("Login successful");
localStorage.setItem('isLoggedIn', "true");
localStorage.setItem('token', this.f.username.value);
this.router.navigate(['/home']);
}
else{
this.message = "Veuillez vérifier vos identifiants";
}
}
}
}


Service:



import { Injectable, OnInit } from "@angular/core";
import { FormBuilder } from "@angular/forms";
import { HttpClient } from '@angular/common/http';

import { Router } from "@angular/router";
import { UserModel } from '../models/user.model';

export enum Endpoints {
login = "/login",
logout = "/LOGOUT",
etc = "/ETC"
}

@Injectable()
export class userService implements OnInit{

//pour connexion au backend
private configJson: any;
private configJsonLogin: any;
private url: string;
public href: string = "";


constructor(private http: HttpClient,
private router: Router,
private _userModel: UserModel,
private formBuilder: FormBuilder
){
}

ngOnInit(){}

async setUrl(){
//connexion au backend
this.configJson = await this.http.get('../../assets/config.json').toPromise();
this.url = this.configJson.url;
console.log(this.url);
}

logout(): void {
localStorage.setItem('isLoggedIn', "false");
localStorage.removeItem('token');
}
}


HTML:



<section class="background">

<form class="connexion" [formGroup]="loginForm" (ngSubmit)="login()" name="form" #f="ngForm">

<mat-form-field [ngClass]="{ 'has-error': submitted && f.userid.errors }">

<label for="email">Email</label>
<input matInput type="text" formControlName="username" name="email" required email />
<div *ngIf="submitted && f.username.errors">
<div *ngIf="f.username.errors.required">Vérifiez votre mail</div>
</div>

</mat-form-field>

<mat-form-field [ngClass]="{ 'has-error': submitted && f.password.errors }">

<label for="password">Password</label>
<input matInput type="password" formControlName="password" name="password" required minlength="8" />
<div *ngIf="submitted && f.password.errors">
<div *ngIf="f.password.errors.required">Vérifiez votre mot de passe</div>
</div>

</mat-form-field>

<div>
<p *ngIf="message">{{message}}</p>
<button mat-raised-button>Connexion</button><br/>
<a routerLink='motdepasse' mat-button>Mot de passe oublié?</a>
</div>

</form>
</section>









share|improve this question
















I made a login connection which is working find.



But this connection has been made with a local connection, in my component.



As I already connected the backend in my Service, how can I check email and password in my database?



Sorry, I'm new in Angular, and dev in general...



Thanks in advance for your help!



Component:



import { Component, NgModule, OnInit } from '@angular/core';
import { ReactiveFormsModule, FormControl, FormGroup, NgForm, FormBuilder, Validators } from '@angular/forms';
import { userService } from '../services/user.service';
import { HttpClientModule } from '@angular/common/http';
import { HttpModule } from '@angular/http';
import { UserModel } from '../models/user.model';
import { Router } from '@angular/router';

@NgModule({
imports: [
ReactiveFormsModule,
FormControl,
FormGroup,
HttpClientModule,
HttpModule
],
})

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit{
model: UserModel = {username: "ambre.naude@infogene.fr", password: "test1234"};
loginForm: FormGroup;
message: string;

loginUserData = {}

constructor(private _userService: userService,
private _userModel: UserModel,
private router: Router,
private formBuilder: FormBuilder) {}

ngOnInit(){
//connexion au backend
this._userService.setUrl();
this._userService

//connexion à l'url du site
/*this._userService.getConfiguration();*/

//pour la fonction de login
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required] });
this._userService.logout();

}
get f() { return this.loginForm.controls; }

login(){
if (this.loginForm.invalid) {
return;
}
else{
if(this.f.username.value == this.model.username && this.f.password.value == this.model.password){
console.log("Login successful");
localStorage.setItem('isLoggedIn', "true");
localStorage.setItem('token', this.f.username.value);
this.router.navigate(['/home']);
}
else{
this.message = "Veuillez vérifier vos identifiants";
}
}
}
}


Service:



import { Injectable, OnInit } from "@angular/core";
import { FormBuilder } from "@angular/forms";
import { HttpClient } from '@angular/common/http';

import { Router } from "@angular/router";
import { UserModel } from '../models/user.model';

export enum Endpoints {
login = "/login",
logout = "/LOGOUT",
etc = "/ETC"
}

@Injectable()
export class userService implements OnInit{

//pour connexion au backend
private configJson: any;
private configJsonLogin: any;
private url: string;
public href: string = "";


constructor(private http: HttpClient,
private router: Router,
private _userModel: UserModel,
private formBuilder: FormBuilder
){
}

ngOnInit(){}

async setUrl(){
//connexion au backend
this.configJson = await this.http.get('../../assets/config.json').toPromise();
this.url = this.configJson.url;
console.log(this.url);
}

logout(): void {
localStorage.setItem('isLoggedIn', "false");
localStorage.removeItem('token');
}
}


HTML:



<section class="background">

<form class="connexion" [formGroup]="loginForm" (ngSubmit)="login()" name="form" #f="ngForm">

<mat-form-field [ngClass]="{ 'has-error': submitted && f.userid.errors }">

<label for="email">Email</label>
<input matInput type="text" formControlName="username" name="email" required email />
<div *ngIf="submitted && f.username.errors">
<div *ngIf="f.username.errors.required">Vérifiez votre mail</div>
</div>

</mat-form-field>

<mat-form-field [ngClass]="{ 'has-error': submitted && f.password.errors }">

<label for="password">Password</label>
<input matInput type="password" formControlName="password" name="password" required minlength="8" />
<div *ngIf="submitted && f.password.errors">
<div *ngIf="f.password.errors.required">Vérifiez votre mot de passe</div>
</div>

</mat-form-field>

<div>
<p *ngIf="message">{{message}}</p>
<button mat-raised-button>Connexion</button><br/>
<a routerLink='motdepasse' mat-button>Mot de passe oublié?</a>
</div>

</form>
</section>






javascript angular login database-connection backend






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 9:56









barbsan

2,43631223




2,43631223










asked Nov 22 '18 at 9:41









Ambre NaudeAmbre Naude

34




34













  • What exactly do you mean by how can I check email and password in my database?

    – SiddAjmera
    Nov 22 '18 at 9:48



















  • What exactly do you mean by how can I check email and password in my database?

    – SiddAjmera
    Nov 22 '18 at 9:48

















What exactly do you mean by how can I check email and password in my database?

– SiddAjmera
Nov 22 '18 at 9:48





What exactly do you mean by how can I check email and password in my database?

– SiddAjmera
Nov 22 '18 at 9:48












2 Answers
2






active

oldest

votes


















0














In order for login to work with a backend, you need, of course, a working backend. Simply creating a login page helps nothing, if you don't have a place to store/check those user accounts.

If you're new to development, I suggest looking at Firebase. It has an authentication service ready to go, as well as storage capabilities.






share|improve this answer
























  • I already created a working backend as I am already connected with my front. I just need to know which function I can make to compare the username and password in the front and the back. Thanks

    – Ambre Naude
    Nov 22 '18 at 9:59













  • Then you need to send the login data to that backend, using the HttpClient the other answer has suggested. Be aware that just sending the username/password in plain text is considered very bad practice.

    – Stybar
    Nov 22 '18 at 10:02



















0














Please alter your component and service like below, hope it make sense for you.



Step 1: Login submit event e.g.:



     onSubmit() {
let reqData: any = {};
reqData.Email = this.loginForm.value.UserName;
reqData.Password = this.loginForm.value.Password;

this._userService.post('/Login', reqData).subscribe(data => {
console.log(data);
}, err => {
console.log('Error');
}, () => { });
}


Step 2: Alter your service accordingly



import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

const httpHeader = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};



@Injectable()
export class userService {
constructor(private http: HttpClient) { }

//Your Service Login Method URL e.g. https://stackoverflow.com/api
post(url: string, jsonBody: any): Observable<any> {
let reqBody = JSON.stringify(jsonBody);
return this.http.post('[Your Service Login Method URL]'+url, reqBody, httpHeader).catch(this.handleError);
}
}


private handleError(httpErrorRes: HttpErrorResponse) {
let errMsg = `${httpErrorRes.error.text}`;
return Observable.throw(errMsg);
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53427918%2fangular6-backend-connection%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    In order for login to work with a backend, you need, of course, a working backend. Simply creating a login page helps nothing, if you don't have a place to store/check those user accounts.

    If you're new to development, I suggest looking at Firebase. It has an authentication service ready to go, as well as storage capabilities.






    share|improve this answer
























    • I already created a working backend as I am already connected with my front. I just need to know which function I can make to compare the username and password in the front and the back. Thanks

      – Ambre Naude
      Nov 22 '18 at 9:59













    • Then you need to send the login data to that backend, using the HttpClient the other answer has suggested. Be aware that just sending the username/password in plain text is considered very bad practice.

      – Stybar
      Nov 22 '18 at 10:02
















    0














    In order for login to work with a backend, you need, of course, a working backend. Simply creating a login page helps nothing, if you don't have a place to store/check those user accounts.

    If you're new to development, I suggest looking at Firebase. It has an authentication service ready to go, as well as storage capabilities.






    share|improve this answer
























    • I already created a working backend as I am already connected with my front. I just need to know which function I can make to compare the username and password in the front and the back. Thanks

      – Ambre Naude
      Nov 22 '18 at 9:59













    • Then you need to send the login data to that backend, using the HttpClient the other answer has suggested. Be aware that just sending the username/password in plain text is considered very bad practice.

      – Stybar
      Nov 22 '18 at 10:02














    0












    0








    0







    In order for login to work with a backend, you need, of course, a working backend. Simply creating a login page helps nothing, if you don't have a place to store/check those user accounts.

    If you're new to development, I suggest looking at Firebase. It has an authentication service ready to go, as well as storage capabilities.






    share|improve this answer













    In order for login to work with a backend, you need, of course, a working backend. Simply creating a login page helps nothing, if you don't have a place to store/check those user accounts.

    If you're new to development, I suggest looking at Firebase. It has an authentication service ready to go, as well as storage capabilities.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 22 '18 at 9:58









    StybarStybar

    1759




    1759













    • I already created a working backend as I am already connected with my front. I just need to know which function I can make to compare the username and password in the front and the back. Thanks

      – Ambre Naude
      Nov 22 '18 at 9:59













    • Then you need to send the login data to that backend, using the HttpClient the other answer has suggested. Be aware that just sending the username/password in plain text is considered very bad practice.

      – Stybar
      Nov 22 '18 at 10:02



















    • I already created a working backend as I am already connected with my front. I just need to know which function I can make to compare the username and password in the front and the back. Thanks

      – Ambre Naude
      Nov 22 '18 at 9:59













    • Then you need to send the login data to that backend, using the HttpClient the other answer has suggested. Be aware that just sending the username/password in plain text is considered very bad practice.

      – Stybar
      Nov 22 '18 at 10:02

















    I already created a working backend as I am already connected with my front. I just need to know which function I can make to compare the username and password in the front and the back. Thanks

    – Ambre Naude
    Nov 22 '18 at 9:59







    I already created a working backend as I am already connected with my front. I just need to know which function I can make to compare the username and password in the front and the back. Thanks

    – Ambre Naude
    Nov 22 '18 at 9:59















    Then you need to send the login data to that backend, using the HttpClient the other answer has suggested. Be aware that just sending the username/password in plain text is considered very bad practice.

    – Stybar
    Nov 22 '18 at 10:02





    Then you need to send the login data to that backend, using the HttpClient the other answer has suggested. Be aware that just sending the username/password in plain text is considered very bad practice.

    – Stybar
    Nov 22 '18 at 10:02













    0














    Please alter your component and service like below, hope it make sense for you.



    Step 1: Login submit event e.g.:



         onSubmit() {
    let reqData: any = {};
    reqData.Email = this.loginForm.value.UserName;
    reqData.Password = this.loginForm.value.Password;

    this._userService.post('/Login', reqData).subscribe(data => {
    console.log(data);
    }, err => {
    console.log('Error');
    }, () => { });
    }


    Step 2: Alter your service accordingly



    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/observable/throw';

    const httpHeader = {
    headers: new HttpHeaders({
    'Content-Type': 'application/json'
    })
    };



    @Injectable()
    export class userService {
    constructor(private http: HttpClient) { }

    //Your Service Login Method URL e.g. https://stackoverflow.com/api
    post(url: string, jsonBody: any): Observable<any> {
    let reqBody = JSON.stringify(jsonBody);
    return this.http.post('[Your Service Login Method URL]'+url, reqBody, httpHeader).catch(this.handleError);
    }
    }


    private handleError(httpErrorRes: HttpErrorResponse) {
    let errMsg = `${httpErrorRes.error.text}`;
    return Observable.throw(errMsg);
    }





    share|improve this answer




























      0














      Please alter your component and service like below, hope it make sense for you.



      Step 1: Login submit event e.g.:



           onSubmit() {
      let reqData: any = {};
      reqData.Email = this.loginForm.value.UserName;
      reqData.Password = this.loginForm.value.Password;

      this._userService.post('/Login', reqData).subscribe(data => {
      console.log(data);
      }, err => {
      console.log('Error');
      }, () => { });
      }


      Step 2: Alter your service accordingly



      import { Injectable } from '@angular/core';
      import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
      import { Observable } from 'rxjs/Observable';
      import 'rxjs/add/operator/catch';
      import 'rxjs/add/observable/throw';

      const httpHeader = {
      headers: new HttpHeaders({
      'Content-Type': 'application/json'
      })
      };



      @Injectable()
      export class userService {
      constructor(private http: HttpClient) { }

      //Your Service Login Method URL e.g. https://stackoverflow.com/api
      post(url: string, jsonBody: any): Observable<any> {
      let reqBody = JSON.stringify(jsonBody);
      return this.http.post('[Your Service Login Method URL]'+url, reqBody, httpHeader).catch(this.handleError);
      }
      }


      private handleError(httpErrorRes: HttpErrorResponse) {
      let errMsg = `${httpErrorRes.error.text}`;
      return Observable.throw(errMsg);
      }





      share|improve this answer


























        0












        0








        0







        Please alter your component and service like below, hope it make sense for you.



        Step 1: Login submit event e.g.:



             onSubmit() {
        let reqData: any = {};
        reqData.Email = this.loginForm.value.UserName;
        reqData.Password = this.loginForm.value.Password;

        this._userService.post('/Login', reqData).subscribe(data => {
        console.log(data);
        }, err => {
        console.log('Error');
        }, () => { });
        }


        Step 2: Alter your service accordingly



        import { Injectable } from '@angular/core';
        import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
        import { Observable } from 'rxjs/Observable';
        import 'rxjs/add/operator/catch';
        import 'rxjs/add/observable/throw';

        const httpHeader = {
        headers: new HttpHeaders({
        'Content-Type': 'application/json'
        })
        };



        @Injectable()
        export class userService {
        constructor(private http: HttpClient) { }

        //Your Service Login Method URL e.g. https://stackoverflow.com/api
        post(url: string, jsonBody: any): Observable<any> {
        let reqBody = JSON.stringify(jsonBody);
        return this.http.post('[Your Service Login Method URL]'+url, reqBody, httpHeader).catch(this.handleError);
        }
        }


        private handleError(httpErrorRes: HttpErrorResponse) {
        let errMsg = `${httpErrorRes.error.text}`;
        return Observable.throw(errMsg);
        }





        share|improve this answer













        Please alter your component and service like below, hope it make sense for you.



        Step 1: Login submit event e.g.:



             onSubmit() {
        let reqData: any = {};
        reqData.Email = this.loginForm.value.UserName;
        reqData.Password = this.loginForm.value.Password;

        this._userService.post('/Login', reqData).subscribe(data => {
        console.log(data);
        }, err => {
        console.log('Error');
        }, () => { });
        }


        Step 2: Alter your service accordingly



        import { Injectable } from '@angular/core';
        import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
        import { Observable } from 'rxjs/Observable';
        import 'rxjs/add/operator/catch';
        import 'rxjs/add/observable/throw';

        const httpHeader = {
        headers: new HttpHeaders({
        'Content-Type': 'application/json'
        })
        };



        @Injectable()
        export class userService {
        constructor(private http: HttpClient) { }

        //Your Service Login Method URL e.g. https://stackoverflow.com/api
        post(url: string, jsonBody: any): Observable<any> {
        let reqBody = JSON.stringify(jsonBody);
        return this.http.post('[Your Service Login Method URL]'+url, reqBody, httpHeader).catch(this.handleError);
        }
        }


        private handleError(httpErrorRes: HttpErrorResponse) {
        let errMsg = `${httpErrorRes.error.text}`;
        return Observable.throw(errMsg);
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 '18 at 9:59









        Sanjay KatiyarSanjay Katiyar

        44018




        44018






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53427918%2fangular6-backend-connection%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            Npm cannot find a required file even through it is in the searched directory

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith