简体   繁体   English

Angular6后端连接

[英]Angular6 backend connection

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... 抱歉,我是Angular的新手,而开发人员一般...

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: 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>

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 . 如果您不熟悉开发,建议您使用Firebase It has an authentication service ready to go, as well as storage capabilities. 它具有随时可用的身份验证服务以及存储功能。

Please alter your component and service like below, hope it make sense for you. 请按如下所示更改您的组件和服务,希望对您有意义。

Step 1: Login submit event eg: 步骤1:登录提交事件,例如:

     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 第2步:相应地更改服务

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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM