Регистрация пользователя. Регистрация пользователя. angular user registration reg

Регистрация пользователя.

Open in new window

Регистрация пользователя.

Создаем компоненты для страницы регистрации и для формы регистрации.

ng g component registration

Создаем модуль для регистрации

ng g module registration/registartion

Подключим модуль регистрации в корневом модуле приложения.

import { RegistrationModule } from './registration/registration.module';


...

  ],
  imports: [
    ...
    RegistrationModule,
   ...
  ],

Сгенерируем компонент для формы.

ng g component registration/form

Роутинг

registration.component';

const routes: Routes = [
  { path: 'index', component: IndexComponent },
  { path: 'login', component: LoginComponent },
  { path: 'registration', component: RegistrationComponent },

Ссылка на роутинг.

Подключаем компонент RegistrationComponent в модуле регистрации.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormComponent } from './form/form.component';
import { RegistrationComponent } from './registration.component';

@NgModule({
  declarations: [
    FormComponent,
    RegistrationComponent
  ],
  imports: [
    CommonModule
  ]
})
export class RegistrationModule { }

Так же подключем модуль для форм FormsModule из коробки Ангуляр.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormComponent } from './form/form.component';
import { RegistrationComponent } from './registration.component';
import { FormsModule }   from '@angular/forms';

@NgModule({
  declarations: [
    FormComponent,
    RegistrationComponent
  ],
  imports: [
    CommonModule,
    FormsModule
  ]
})
export class RegistrationModule { }

Шаблон формы.

<div class="mx-auto login_form">

  <form #regForm="ngForm" method="post">
    <h2 class="text-center">Registration</h2>


    <div class="form-group">
        <label>Username</label>
        <input type="text" class="form-control" [(ngModel)]="userdata.username"  name="username" required="required">
    </div>
    <div class="form-group">
      <label>Email address</label>
      <input type="text" class="form-control" [(ngModel)]="userdata.email"  name="email" required="required">
    </div>
    <div class="form-group">
        <label for="">Password</label>
        <input type="password" class="form-control" name="password" [(ngModel)]="userdata.password"  required="required" #password="ngModel">

    </div>
    <div class="form-group">
      <label for="">Repeat password</label>
      <input [(ngModel)]="userdata.repeatpassword" type="password" class="form-control" name="confirmpassword"  required="required" #confirmpassword="ngModel" pattern="{{ password.value }}">
  </div>
    <div class="form-group">
        <button (click)="login()" type="submit" class="btn btn-primary btn-block">Log in</button>
    </div>
  </form>
</div>

Определим модель где будем хранить данные с формы.

export class FormComponent implements OnInit {

  userdata: any = {
     "email": '',
     "username": '',
     "password": '',
     "repeatpassword": ''
    };

Валидация паролей.

Источник

<div *ngIf="password.invalid && (regForm.submitted || password.touched)" class="alert alert-danger">
  <div *ngIf="password.errors.required"> Password is required. </div>
  <div *ngIf="confirmpassword.errors.pattern"> Password & Confirm Password does not match.</div>
</div>

<div *ngIf=" confirmpassword.invalid && (regForm.submitted || confirmpassword.touched)" class="alert alert-danger">
  <div *ngIf="confirmpassword.errors.required"> Confirm password is required. </div>
  <div *ngIf="confirmpassword.errors.pattern"> Password & Confirm Password does not match.</div>
</div>

registration angular

Запрос на сервер.

ng g service registration/registration

Опишем сервис.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { API_URL } from '../global';

@Injectable({
  providedIn: 'root'
})
export class RegistrationService {

  constructor(private http: HttpClient) {
   }

   save(data: any){
    return this.http.post(API_URL+'api/register', data);
   }


}

Использование сервиса в компоненте.

...
import { RegistrationService } from './registration.service';
import { AlertService } from '../directives/alert.service';


export class RegistrationComponent implements OnInit {


  ...

  constructor(
      private http: RegistrationService,
      private alert: AlertService
      ) { }

  ...

  register() {

    this.http.save(this.userdata).subscribe((res: any) => {
      if(res.status==0){
        this.alert.success(res.message);
      } else {
        this.alert.error(res.message);
      }
    });

  }

}

Редирект на страницу регистрации.

import {Router} from "@angular/router";

...

constructor(
  private http: RegistrationService,
  private alert: AlertService,
  private router: Router
  ) { }    
  ...
  this.router.navigate(['/login']);
  if(res.status==0){
    this.alert.success(res.message);
  } else ...

registration angular

Other topics