Angular+WebAPI入门示例(二)

上篇文章https://blog.csdn.net/liwan09/article/details/82288470主要讲的是初步的环境搭建,这里主要讲下相关功能的具体实现

一、登录功能

1、打开创建的accountinfoservice服务 accountinfo.service.ts文件,导入http、Observable、以及创建的三个实体类

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { Userinfo } from '../models/userinfo';
import { Account } from '../models/account';
import { Msg } from '../models/msg';

2、服务中创建一个私有的http,注入到构造函数中

//构造函数
  constructor(private http: HttpClient) { }

 3、服务中创建登录方法

 //登录
  login(loginInfo: Userinfo): Observable<Account> {
    return this.http.post<Account>('/api/AccountInfo/Login', loginInfo);
  }

4、打开login.component.ts文件,将代码改为

import { Component, OnInit, Input } from '@angular/core';
import { AccountinfoService } from '../../service/accountinfo.service';
import { Userinfo } from '../../models/userinfo';
import { RouterLink, Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  user: Userinfo = new Userinfo();
  constructor(private accountservice: AccountinfoService, private router: Router) { }

  ngOnInit() {

  }
  //登录
  login(): void {
    this.accountservice.login(this.user).subscribe(res => {
      if (res == null) {
        alert('用户名或者密码错误!');
      }
      else {
        //路由跳转到列表页面
        this.router.navigate(['/accountlist']);
      }
    });
  }
}

 在路由配置页,添加列表页的路由配置

{ path: 'accountlist', component: AccountlistComponent }

登录页面的登录按钮的添加事件(click)="login()" 

二、数据列表页

此页面包含增删改查的功能

1、路由中定义编辑页面的配置

{ path: 'accountedit/:id', component: AccounteditComponent }

2、在服务中,添加相关的方法

//获取数据列表
  getAccountList(): Observable<Account[]> {
    return this.http.get<Account[]>('/api/AccountInfo/GetList');
  }

  //获取数据
  getAccountModel(accountid: string): Observable<Account> {
    let para = { accountID: accountid };
    return this.http.get<Account>('/api/AccountInfo/GetModel', { params: para });
  }
  //保存
  save(saveinfo: Account): Observable<Msg> {
    return this.http.post<Msg>('/api/AccountInfo/Save', saveinfo);
  }
  //删除
  deleteaccount(accountid: string): Observable<Msg> {
    let para = { accountID: accountid };
    return this.http.delete<Msg>('/api/AccountInfo/Delete', { params: para });
  }

 3、列表页面html列表页面

<div class="container" style="padding-top:50px">
  <div class="form-group">
    <button class="btn btn-primary" routerLink="/accountedit/''">新增</button>
  </div>
  <table class="table table-bordered table-hover table-striped">
    <thead>
      <tr>
        <th>用户姓名</th>
        <th>登录账号</th>
        <th>创建时间</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of accountlist">
        <td>{{item.UserName}}</td>
        <td>{{item.LoginID}}</td>
        <td>{{item.CreateTime| date:'yyyy-MM-dd HH:mm:ss'}}</td>
        <td>
          <button type="button" class="btn btn-link" routerLink="/accountedit/{{item.AccountID}}">编辑</button>
          <button type="button" class="btn btn-link" (click)="deletedata(item.AccountID)">删除</button>
        </td>
      </tr>
    </tbody>
  </table>
</div>

 后台代码

import { Component, OnInit, Input } from '@angular/core';
import { AccountinfoService } from '../../service/accountinfo.service';
import { Account } from '../../models/account';

@Component({
  selector: 'app-accountlist',
  templateUrl: './accountlist.component.html',
  styleUrls: ['./accountlist.component.css']
})
export class AccountlistComponent implements OnInit {

  accountlist: Account[];//用户列表全局变量
  constructor(private accountservice: AccountinfoService) { }

  ngOnInit() {
    this.getAccoutList();
  }
  //获取用户列表
  getAccoutList(): void {
    this.accountservice.getAccountList().subscribe(res => this.accountlist = res);
  }
  //删除
  deletedata(id: string) {
    if (confirm("确定要删除吗?")) {
      this.accountservice.deleteaccount(id).subscribe(res => {
        if (res.message == "success") {
          alert('删除成功!');
          //重新加载数据
          this.getAccoutList();
        }
        else {
          alert('删除失败!');
        }
      })
    }
  }

}

编辑页面html代码

<form class="form-horizontal" style="width:300px;height:300px;margin:0 auto;padding-top:200px">
  <div class="form-group">
    <label class="sr-only" for="username">用户姓名</label>
    <input type="hidden" id="accountid" name="accountid" [(ngModel)]="account.AccountID" #accountid="ngModel">
    <input type="hidden" id="createtime" name="createtime" [(ngModel)]="account.CreateTime" #createtime="ngModel">
    <input type="hidden" id="modifytime" name="modifytime" [(ngModel)]="account.ModifyTime" #modifytime="ngModel">
    <input type="text" class="form-control" id="username" name="username" [(ngModel)]="account.UserName" #username="ngModel"
      placeholder="用户姓名" required>
  </div>
  <div class="form-group">
    <label class="sr-only" for="loginid">登录账号</label>
    <input type="text" class="form-control" id="loginid" name="loginid" [(ngModel)]="account.LoginID" #loginid="ngModel" placeholder="登录账号"
      required>
  </div>
  <div class="form-group">
    <label class="sr-only" for="passWord">密码</label>
    <input type="password" class="form-control" id="passWord" name="passWord" [(ngModel)]="account.PassWord" #passWord="ngModel"
      placeholder="密码" required>
  </div>
  <button class="btn btn-primary" (click)="saveAccount()">保存</button>
</form>

后台代码

import { Component, OnInit, Input } from '@angular/core';
import { Location } from '@angular/common';
import { RouterLink, Router, Route, ActivatedRoute } from '@angular/router';
import { AccountinfoService } from '../../service/accountinfo.service';
import { Account } from '../../models/account';

@Component({
  selector: 'app-accountedit',
  templateUrl: './accountedit.component.html',
  styleUrls: ['./accountedit.component.css']
})
export class AccounteditComponent implements OnInit {
  account: Account = new Account();
  constructor(private accountservice: AccountinfoService, private location: Location, private route: ActivatedRoute) { }

  ngOnInit() {
    this.getModel();
  }
  //获取数据实体
  getModel(): void {
    let accountid = this.route.snapshot.paramMap.get('id');//获取路由传参
    if (accountid != null && accountid != "") {
      this.accountservice.getAccountModel(accountid).subscribe(res => {
        if (res != null) {
          this.account = res;
        }
      });
    }
  }
  //保存
  saveAccount(): void {
    this.accountservice.save(this.account).subscribe(res => {
      if (res.message == "success") {
        alert('操作成功!');
        this.location.back();
      }
      else {
        alert('操作失败!');
      }
    });
  }
}

ng serve  启动,运行操作效果

程序源码下载地址https://download.csdn.net/download/liwan09/10640044

猜你喜欢

转载自blog.csdn.net/liwan09/article/details/82289109