Angular 11,Typescript,Nodejs,mysql - 如果注册组件上的电子邮件域正确,则在主页组件中显示基于 'mysql' 布尔值的按钮

Angular 11, Typescript, Nodejs, mysql - If email domain correct on register component, show button based on 'mysql' Boolean value, in home component

目前正在尝试在我的应用程序中添加在注册过程中检查特定域电子邮件地址的功能,基于此,用户稍后将在 'home' 页面上看到一个特定按钮。 (类似;如果@hotmail.com 电子邮件,patchValue('1')。然后如果'0',隐藏按钮,如果'1',显示按钮。)

电子邮件 'check' 在我的 'isTestEmail' 函数中完成,在 'register.component.ts' 中,根据我的 console.log 输出,检查工作正常。

接下来,在相同的函数中,如果输入了所需的电子邮件地址,我想在帐户数据库 table 中设置一个值 (isLecturer),从“0”到“1”。

然后在我的 'home.component.html' 中显示或隐藏特定按钮(使用 ngIf),基于 mySQL 帐户 table 属性 (isLecturer) 值为 0或 1 (true/false).

我的问题是我不确定在我的 'isTestEmail' 函数中放入正确的语法,这会将数据库中的值从 0 更改为 1。

我也不确定要在 'lab-swap-home.component.ts' 中添加什么代码来帮助检测 'lab-swap-home.component.html' 中的 NgIf 语句。

我对我提出的解决方案没有信心,可能是想多了。我很乐意看到任何更简单的建议来实现此功能。

数据库 > 帐户 table > isLecturer 配置:

register.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.log('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.log("TEST EMAIL VALID");
                this.isLecturer.patchValue('1'); // Intended way.
                this.isLecturer = false; // optional way, unsure how to implement.
            }
            else{
                console.log("TEST EMAIL INVALID");
            }

        //}
    }

    // convenience getter for easy access to form fields
    get f() { return this.form.controls; }

    onSubmit() {
        this.submitted = true;

        console.log('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);
}

我相信通过将 'isTestEmail' 函数移动到 'home' 组件中并通过在页面初始化期间调用该函数检查当前用户帐户电子邮件来解决我自己的问题。然后根据当前用户的电子邮件域隐藏/显示按钮。

设法获得正确的语法,在 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.log("TEST EMAIL INVALID");
            }

        //}
    }