В настоящее время пытаюсь добавить в свое приложение функциональность, которая проверяла бы определенный адрес электронной почты домена во время регистрации, и на основе этого пользователь позже увидит определенную кнопку на «домашней» странице. (Что-то вроде: Если адрес электронной почты @hotmail.com, patchValue('1'). Затем, если '0', скрыть кнопку, если '1', показать кнопку.)
«Проверка» электронной почты выполняется в моей функции «isTestEmail», в «register.component.ts», и проверка работает правильно на основе моего вывода console.info.
Затем в той же функции я хочу установить значение (isLecturer) в таблице учетных записей БД от «0» до «1», если был введен нужный адрес электронной почты.
Затем в моем 'home.component.html' покажите или скройте определенную кнопку (используя ngIf), основываясь на значении этого свойства таблицы учетной записи mySQL (isLecturer) 0 или 1 (true/false).
Моя проблема в том, что я не уверен в правильном синтаксисе моей функции isTestEmail, которая изменит значение в базе данных с 0 на 1.
Я также не уверен, какой код добавить в «lab-swap-home.component.ts», чтобы облегчить обнаружение оператора NgIf в «lab-swap-home.component.html».
Я не уверен в своем предложенном решении и мог бы слишком много думать об этом. Я хотел бы увидеть любые более простые предложения по реализации этой функции.
База данных > Таблица учетных записей > Конфигурация isLecturer:
регистр.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { first } from 'rxjs/operators';
import { AccountService, AlertService } from '@app/_services';
import { MustMatch } from '@app/_helpers';
import { Account } from '@app/_models/account'; //
@Component({ templateUrl: 'register.component.html' })
export class RegisterComponent implements OnInit {
form: FormGroup;
loading = false;
submitted = false;
email: any;
//isLecturer: boolean = true; //optional way, unsure.
//isLecturer: any;
constructor(
private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private accountService: AccountService,
private alertService: AlertService
) { }
ngOnInit() {
this.form = this.formBuilder.group({
title: ['', Validators.required],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]],
confirmPassword: ['', Validators.required],
acceptTerms: [false, Validators.requiredTrue],
//isLecturer: ['', Validators.required],
}, {
validator: MustMatch('password', 'confirmPassword')
});
}
public TestFunc() {
console.info('Function is called')
}
public isTestEmail() {
// var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
// if (re.test(email)){
//Email valid. Procees to test if it's from the right domain (Second argument is to check that the string ENDS with this domain, and that it doesn't just contain it)
if (this.form.controls.email.value.indexOf("@hotmail.com", this.form.controls.email.value.length - "@hotmail.com".length) !== -1){
//VALID
console.info("TEST EMAIL VALID");
this.isLecturer.patchValue('1'); // Intended way.
this.isLecturer = false; // optional way, unsure how to implement.
}
else{
console.info("TEST EMAIL INVALID");
}
//}
}
// convenience getter for easy access to form fields
get f() { return this.form.controls; }
onSubmit() {
this.submitted = true;
console.info('LOOK!')
this.TestFunc(); // calling function this way works!
this.isTestEmail();
//this.accountService.isTestEmail
//this.accountService.TestFunc
// reset alerts on submit
this.alertService.clear();
// stop here if form is invalid
if (this.form.invalid) {
return;
}
this.loading = true;
this.accountService.register(this.form.value)
.pipe(first())
.subscribe({
next: () => {
this.alertService.success('Registration successful, please check your email for verification instructions', { keepAfterRouteChange: true });
this.router.navigate(['../login'], { relativeTo: this.route });
},
error: error => {
this.alertService.error(error);
this.loading = false;
}
});
}
}
(модель) account.ts:
import { Role } from './role';
export class Account {
id: string;
title: string;
firstName: string;
lastName: string;
email: string;
role: Role;
jwtToken?: string;
isLecturer?: boolean;
}
Пример кнопки lab-swap-home.component.html:
<button (click) = "openModal('custom-modal-1')" *ngIf = "isLecturer === '1'" class = "btn btn-primary mr-2 mb-3 ml-3" >Create available lab slots</button>
account.model.js (бэкенд):
const { DataTypes } = require('sequelize');
module.exports = model;
function model(sequelize) {
const attributes = {
email: { type: DataTypes.STRING, allowNull: false },
passwordHash: { type: DataTypes.STRING, allowNull: false },
title: { type: DataTypes.STRING, allowNull: false },
firstName: { type: DataTypes.STRING, allowNull: false },
lastName: { type: DataTypes.STRING, allowNull: false },
acceptTerms: { type: DataTypes.BOOLEAN },
isLecturer: { type: DataTypes.BOOLEAN },
isStudent: { type: DataTypes.BOOLEAN },
role: { type: DataTypes.STRING, allowNull: false },
verificationToken: { type: DataTypes.STRING },
verified: { type: DataTypes.DATE },
resetToken: { type: DataTypes.STRING },
resetTokenExpires: { type: DataTypes.DATE },
passwordReset: { type: DataTypes.DATE },
created: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW },
updated: { type: DataTypes.DATE },
isVerified: {
type: DataTypes.VIRTUAL,
get() { return !!(this.verified || this.passwordReset); }
}
};
const options = {
// disable default timestamp fields (createdAt and updatedAt)
timestamps: false,
defaultScope: {
// exclude password hash by default
attributes: { exclude: ['passwordHash'] }
},
scopes: {
// include hash with this scope
withHash: { attributes: {}, }
}
};
return sequelize.define('account', attributes, options);
}
🤔 А знаете ли вы, что...
MySQL поддерживает множество операционных систем, включая Linux, Windows и macOS.
Я считаю, что решил свою проблему, переместив функцию «isTestEmail» в «домашний» компонент и проверив электронную почту учетной записи текущего пользователя, вызвав функцию во время инициализации страницы. Затем кнопка скрывается/отображается в зависимости от домена электронной почты текущего пользователя.
Удалось получить правильный синтаксис, В html:
*ngIf = "isLecturer === true"
И home.component.ts:
isLecturer: boolean = false
public isTestEmail() {
if (this.account.email.indexOf("@mail.com", this.account.email.length - "@mail.com".length) !== -1){
this.isLecturer = true;
}
else{
console.info("TEST EMAIL INVALID");
}
//}
}