首页 > 其他分享 >334 Login UI

334 Login UI

时间:2024-06-30 18:27:18浏览次数:3  
标签:334 component ts angular UI import Login null login

步骤

1、login-user.ts

运行如下命令

ng g class models\LoginUser

生成的login-user.ts更新后显示如下

export class LoginUser {
  email: string | null = null;
  password: string | null = null;
}

2、account.service.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { LoginUser } from '../models/login-user';
import { RegisterUser } from '../models/register-user';
const API_BASE_URL: string = "https://localhost:7173/api/v1/account/";
@Injectable({
  providedIn: 'root'
})
export class AccountService {
  public currentUserName: string | null = null;
  constructor(private httpClient: HttpClient) {
  }
  public postRegister(registerUser: RegisterUser): Observable<RegisterUser> {
    return this.httpClient.post<RegisterUser>(`${API_BASE_URL}register`, registerUser);
  }
  public postLogin(loginUser: LoginUser): Observable<LoginUser> {
    return this.httpClient.post<LoginUser>(`${API_BASE_URL}login`, loginUser);
  }
  public getLogout(): Observable<string> {
    return this.httpClient.get<string>(`${API_BASE_URL}logout`);
  }
}

3、login.component.ts

运行如下命令

ng g component Login

生成的login.component.ts更新后显示如下

import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { LoginUser } from '../models/login-user';
import { AccountService } from '../services/account.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  loginForm: FormGroup;
  isLoginFormSubmitted: boolean = false;


  constructor(private accountService: AccountService, private router: Router) {
    this.loginForm = new FormGroup({
      email: new FormControl(null, [Validators.required, Validators.email]),
      password: new FormControl(null, [Validators.required]),
    });
  }


  get login_emailControl(): any {
    return this.loginForm.controls["email"];
  }

  get login_passwordControl(): any {
    return this.loginForm.controls["password"];
  }


  loginSubmitted() {
    this.isLoginFormSubmitted = true;

    if (this.loginForm.valid) {

      this.accountService.postLogin(this.loginForm.value).subscribe({
        next: (response: LoginUser) => {
          console.log(response);

          this.isLoginFormSubmitted = false;
          this.accountService.currentUserName = response.email;

          this.router.navigate(['/cities']);

          this.loginForm.reset();
        },

        error: (error) => {
          console.log(error);
        },

        complete: () => { },
      });
    }
  }
}

4、login.component.html

<div class="w-75 margin-auto">
  <div class="form-container">

    <h2>Login</h2>

    <form [formGroup]="loginForm" (ngSubmit)="loginSubmitted()">


      <!-- email -->
      <div class="form-field flex">
        <div class="w-25">
          <label for="email" class="form-label pt">Email</label>
        </div>

        <div class="flex-1">
          <input type="text" id="email" class="form-input" formControlName="email" />
          <span class="text-red" *ngIf="(login_emailControl.touched || isLoginFormSubmitted) && (login_emailControl.errors?.['required'])">Email can't be blank</span>
        </div>
      </div>



      <!-- password -->
      <div class="form-field flex">
        <div class="w-25">
          <label for="password" class="form-label pt">Password</label>
        </div>

        <div class="flex-1">
          <input type="password" id="password" class="form-input" formControlName="password" />
          <span class="text-red" *ngIf="(login_passwordControl.touched || isLoginFormSubmitted) && (login_passwordControl.errors?.['required'])">Password can't be blank</span>
        </div>
      </div>



      <!-- submit -->
      <div class="form-field flex">
        <div class="w-25">
        </div>

        <div class="flex-1">
          <button type="submit" class="button button-green-back">Login</button>
        </div>
      </div>

    </form>

  </div>
</div>

5、app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CitiesComponent } from './cities/cities.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
const routes: Routes = [
  { path: "cities", component: CitiesComponent },
  { path: "register", component: RegisterComponent },
  { path: "login", component: LoginComponent }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

6、app.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AccountService } from './services/account.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(public accountService: AccountService, private router: Router) { }

  onLogOutClicked() {
    this.accountService.getLogout().subscribe({
      next: (response: string) => {
        this.accountService.currentUserName = null;

        this.router.navigate([ '/login' ]);
      },

      error: (error) => {
        console.log(error);
      },

      complete: () => { },
    });
  }
}

7、app.component.html

<div class="container">
  <div class="page-content">

    <div class="margin-bottom">
      <div class="flex">

        <div class="flex-1" id="top-bar-div">
          <h2 class="app-title">
            Cities Manager
          </h2>
        </div>

        <div class="flex-1" id="search-box-div">
          <div class="navbar account-links">

            <ul *ngIf="accountService.currentUserName === '' || accountService.currentUserName === null || accountService.currentUserName === undefined">
              <li>
                <a [routerLink]="[ '/login' ]">Login</a>
              </li>

              <li>
                <a [routerLink]="[ '/register' ]">Register</a>
              </li>
            </ul>

            <ul *ngIf="accountService.currentUserName !== '' && accountService.currentUserName !== null && accountService.currentUserName !== undefined">
              <li>
                <a href="#" onclick="return false" (click)="onLogOutClicked()">Logout</a>
              </li>
            </ul>

          </div>
        </div>
      </div>
    </div>


    <div class="navbar mb">
      <ul>
        <li>
          <a [routerLink]="[ '/cities']" [routerLinkActive]="[ 'nav-active']">Cities</a>
        </li>
      </ul>
    </div>


    <div class="body">
      <router-outlet></router-outlet>
    </div>
  </div>
</div>

结果

程序运行后,可以Login/Logout。

Gitee获取源码:

https://gitee.com/huang_jianhua0101/asp.-net-core-8.git

标签:334,component,ts,angular,UI,import,Login,null,login
From: https://blog.csdn.net/KevinHuang2088/article/details/140084295

相关文章

  • EVASH Ultra EEPROM Development Board User Guide
    EVASHUltraEEPROMDevelopmentBoardUserGuideIntroductionWelcometotheEVASHUltraEEPROMDevelopmentBoardUserGuide.ThisguidewillprovideyouwithcomprehensiveinstructionsonhowtousetheEVASHUltraEEPROMDevelopmentBoard,featuringthe......
  • [题解]CF1714F Build a Tree and That Is It
    思路由于题目中说这是一棵无根树,不太方便思考,于是,我们可以假装把这棵树看做有根树。首先我们令\(d_1,d_2,d_3\)分别表示从根节点到节点\(1,2,3\)的长度(不算相交部分)。那么我们可以得到下式:\[\left\{\begin{matrix}d_{12}=d_1+d_2\\d_{13}=d_1+d_3\\......
  • m基于深度学习的卫星遥感图像轮船检测系统matlab仿真,带GUI操作界面
    1.算法仿真效果matlab2022a仿真结果如下:      2.算法涉及理论知识概要      在卫星遥感图像轮船检测中,常用的深度学习模型主要包括卷积神经网络(CNN)、循环神经网络(RNN)、以及两者的混合模型,但最常使用的还是基于CNN的模型,特别是那些在目标检测任务中表现出......
  • 如何实现ElementUI动态表头?
    可能看到这个标题,有些小伙伴会有些疑惑,动态表头是个什么东西,怎么没听说过?其实动态表头在企业的项目中用途还是非常广泛的,比如erp系统什么的那么动态表头是什么呢?说简单点就是让ElementUI的Table表格可以实现自定义表头展示+表头拖拽排序的一个功能这个东西我们肯定有很多小......
  • mosquitto
    mosquitto.confmosquitto.conf是mosquitto的配置文件,#Configfileformosquitto#=================================================================#Generalconfiguration#=================================================================per_listener_setti......
  • Python自动化神器:如何用PyAutoGUI模拟滚轮动一次
    哈喽,大家好,我是木头左!一、PyAutoGUI简介PyAutoGUI是一个纯Python的GUI自动化工具,其目的是可以用程序控制鼠标和键盘操作。它主要在三个方面发挥作用:1)对屏幕上的图像进行识别;2)控制鼠标和键盘的操作;3)具有强大的截图功能。二、安装PyAutoGUI使用PyAutoGUI之前,需要先进行安装。......
  • 【七】【QT开发应用】跨UI发送信号,跨线程发送信号
    跨UI发送信号基本框架新建窗口自定义信号跨线程发送信号新建线程查看线程号完整代码跨UI发送信号setdialog.h#ifndefSETDIALOG_H#defineSETDIALOG_H#include<QDialog>namespaceUi{classsetdialog;}class......
  • 【QML】用 Image(QQuickPaintedItem) 显示图片
    大体功能:频繁地往界面推送图片,帧率达到视频效果。捕获画布上的鼠标事件和键盘事件。代码如下://DrawImageInQQuickPaintedItem.pro代码如下:QT+=quick#YoucanmakeyourcodefailtocompileifitusesdeprecatedAPIs.#Inordertodoso,uncommentthefo......
  • unity麦扣x唐老狮3DRPG笔记分享,ProBuilder插件基本介绍(持续更新)
    声明:本文仅用于个人笔记及学习交流,禁止用作任何商业用途唐老师没有讲过这些插件,所以现在还没轮结合到唐老狮的课程的阶段在具体写代码以及介绍unity本体功能的时候唐老师的课程知识点会融入进来另外该插件功能过多,而用的较少所以很多功能就只做介绍,知道大概即可  首......
  • juicefs cubefs 等元数据分离文件系统分析
    在近期我看到过国外一个大牛开发的hpfshttps://mp.csdn.net/mp_blog/creation/editor/139739977(请看我前面发的片文章)我瞬间就想到国内同类似产品juicefscubefs这两个东西,当时这种产品出现我就有一个疑问,为什么要把元数据单独弄个数据库去存呢?你还要开发数据冗余机制去保......