Angular6后端连接

时间:2018-11-22 09:41:21

标签: javascript angular login database-connection backend

我建立了一个可以找到的登录连接。

但是,此连接是通过我的组件中的本地连接建立的。

当我已经在服务中连接了后端时,如何检查数据库中的电子邮件和密码?

对不起,我是Angular的新手,而开发人员一般...

在此先感谢您的帮助!

组件:

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

服务:

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>

2 个答案:

答案 0 :(得分:0)

为了使登录能够与后端一起使用,您当然需要一个有效的后端。如果您没有存储/检查这些用户帐户的位置,那么仅创建登录页面无济于事。
如果您不熟悉开发,建议您查看Firebase。它具有随时可用的身份验证服务以及存储功能。

答案 1 :(得分:0)

请按如下所示更改组件和服务,希望对您有意义。

步骤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');        
          }, () => { });
      }

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