第一部分: http://www.cnblogs.com/cgzl/p/7755801.html

第二部分: http://www.cnblogs.com/cgzl/p/7763397.html

第三部分: http://www.cnblogs.com/cgzl/p/7768147.html

后台代码: https://github.com/solenovex/asp.net-core-2.0-web-api-boilerplate

前台代码: https://github.com/solenovex/angular-4-client-panel-app

Auth Guard

该系统的大部分页面都应该是用户登陆以后才可以看见, 没有登陆的话直接应该跳转到登陆页面.

首先建立authguard:

ng g g guards/auth

代码:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { User } from 'oidc-client';
import { AuthService } from '../services/auth.service';@Injectable()
export class AuthGuard implements CanActivate {constructor(private router: Router,private authService: AuthService) { }canActivate(): Observable<boolean> {return this.authService.loginStatusChanged.map((user: User) => {if (user) {return true;}this.authService.login();return false;});}
}

然后在app.module.ts里面引用并注册:

import { AuthGuard } from './guards/auth.guard';const appRoutes: Routes = [{ path: '', component: DashboardComponent, canActivate: [AuthGuard] },{ path: 'login-callback', component: LoginCallbackComponent },{ path: 'register', component: RegisterComponent },{ path: 'add-client', component: AddClientComponent, canActivate: [AuthGuard] },{ path: 'client/:id', component: ClientDetailsComponent, canActivate: [AuthGuard] },{ path: 'edit-client/:id', component: EditClientComponent, canActivate: [AuthGuard] }
];providers: [ClientService,AuthService,AuthGuard],

需要权限控制的路由需要加上 canActivate属性, 它的值是一个数组可以使用多个guards.

别忘了在providers里面注册一下.

然后运行.

进入首页 http://localhost:4200, 如果没登陆, 那么直接跳转到authorization server的登陆页面.

登录成功后, 会跳转到login-callback, 这里有一个地方需要改一下(可能是oidc-client的bug?):

ngOnInit() {this.authService.loginCallBack().subscribe((user: User) => {if (user) { window.location.href = '/';}});}

使用的是window.location.href='/', 如果使用angular的路由router.navigate跳转的话会有问题.

登陆成功后跳转到主页.

做一些清理工作:

由于用户注册是在authorization server进行的, 所以把angular项目中的相关文件以及app.module里面的调用删除...

Settings 系统设置

我们需要做一些全局的设置, 可以全局控制某些参数, 例如我们的余额是否可以输入.

建立settings service:

ng g s services/settings

建立settings model:

ng g interface models/Settings

生成的文件名首字母是小写的, 首字母还是改成大写的吧...

Settings.ts:

export interface Settings {disableBalanceOnAdd?: boolean;disableBalanceOnEdit?: boolean;
}

settings.service.ts:

import { Injectable } from '@angular/core';
import { Settings } from '../models/Settings';@Injectable()
export class SettingsService {private _settings: Settings = {disableBalanceOnAdd: false,disableBalanceOnEdit: false};constructor() { }get settings() {return this._settings;}
}

然后再app.module.ts里面注册:

import { SettingsService } from './services/settings.service';
providers: [ClientService,AuthService,SettingsService,AuthGuard]

然后我们使用settings service.

在add-client.component.ts里面:

import { SettingsService } from '../../services/settings.service';public disableBalanceOnAdd = false;constructor(public flashMessagesService: FlashMessagesService,public router: Router,public clientService: ClientService, public settingsService: SettingsService) { }ngOnInit() {this.disableBalanceOnAdd = this.settingsService.settings.disableBalanceOnAdd;}

然后运行一下:

发现点击添加按钮不起作用!!!!, 点击明细也不起作用!!!!

后来发现, 是auth service和auth guard里面写错了, 先修改auth service:

  tryGetUser() {return Observable.fromPromise(this.manager.getUser());}

把这个方法改成public的.

然后修改: auth guard:

  canActivate(): Observable<boolean> {return this.authService.tryGetUser().map((user: User) => {if (user) {return true;}this.authService.login();return false;});}

这次再试试, 就没有问题了. 进入添加客户页面.

这个栏位的状态会根据settings里面的设置而变化.

同样在edit-client里面修改一下:

import { SettingsService } from '../../services/settings.service';disableBalanceOnEdit = false;constructor(public clientService: ClientService,public router: Router,public route: ActivatedRoute,public flashMessagesService: FlashMessagesService, public settingsService: SettingsService) { }ngOnInit() {this.disableBalanceOnEdit = this.settingsService.settings.disableBalanceOnEdit;// 获取IDthis.id = this.route.snapshot.params['id'];// 获取Clientthis.clientService.getOne(+this.id).subscribe(client => {this.client = client;});}

运行一下, 应该好用!

最后, 做一下Settings页面

需要改一下setting.serviec, 将使用localstorage来存储settings:

import { Injectable } from '@angular/core';
import { Settings } from '../models/Settings';@Injectable()
export class SettingsService {private _settings: Settings = {disableBalanceOnAdd: true,disableBalanceOnEdit: false};constructor() {if (localStorage.getItem('settings')) {this._settings = JSON.parse(localStorage.getItem('settings'));}}get settings() {return this._settings;}set settings(value: Settings) {this._settings = value;localStorage.setItem('settings', JSON.stringify(this._settings));}
}

然后打开settings.component.ts:

import { Component, OnInit } from '@angular/core';
import { SettingsService } from '../../services/settings.service';
import { Router } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { Settings } from '../../models/Settings';@Component({selector: 'app-settings',templateUrl: './settings.component.html',styleUrls: ['./settings.component.css']
})
export class SettingsComponent implements OnInit {settings: Settings;constructor(private settingsService: SettingsService,private flashMessagesService: FlashMessagesService,private router: Router) { }ngOnInit() {this.settings = this.settingsService.settings;}onSubmit() {this.settingsService.settings = this.settings;this.flashMessagesService.show('Settings 保存了', { cssClass: 'alert-success', timeout: 4000 });}}

这个很简单.

然后是html:

<div class="row"><div class="col-md-6"><a routerLink="/" class="btn btn-link"><i class="fa fa-arrow-circle-o-left"></i> 回到Dashboard</a></div><div class="col-md-6"></div>
</div><div class="card"><div class="card-header"><h3>编辑 Settings</h3></div><div class="card-body"><form (submit)="onSubmit()"><div class="form-group"><label for="disableBalanceOnAdd">Disable Blance on Add</label><input type="checkbox" id="disableBalanceOnAdd" name="disableBalanceOnAdd" [(ngModel)]="settings.disableBalanceOnAdd"></div><div class="form-group"><label for="disableBalanceOnEdit">Disable Blance on Edit</label><input type="checkbox" id="disableBalanceOnEdit" name="disableBalanceOnEdit" [(ngModel)]="settings.disableBalanceOnEdit"></div><input type="submit" class="btn btn-primary btn-block" value="Submit"></form></div>
</div>

别忘了在app.module里面添加路由:

const appRoutes: Routes = [{ path: '', component: DashboardComponent, canActivate: [AuthGuard] },{ path: 'login-callback', component: LoginCallbackComponent },{ path: 'add-client', component: AddClientComponent, canActivate: [AuthGuard] },{ path: 'client/:id', component: ClientDetailsComponent, canActivate: [AuthGuard] },{ path: 'edit-client/:id', component: EditClientComponent, canActivate: [AuthGuard] }, { path: 'settings', component: SettingsComponent, canActivate: [AuthGuard] },{ path: '**', component: PageNotFoundComponent }
];

顺便把page Not found的路由也加上, 使用 ** wildcard.

最后在navbar.html 添加上链接按钮:

        <li *ngIf="isLoggedIn" class="nav-item"><a class="nav-link" href="#" routerLink="/settings">Settings </a></li>

运行一下试试:

刷新, 查看添加和编辑页面,再刷新, 应该好用.

这个联系项目就到这了.

然后我要用asp.net core 2.0 web api 和 identity server 4 以及 angular 5 做一个项目了(angular 5正式版刚刚出来), 大约 300个页面......

也许之前还要做一个练习..请各位指教...

转载于:https://www.cnblogs.com/cgzl/p/7776378.html

使用angular4和asp.net core 2 web api做个练习项目(四)相关推荐

  1. 使用angular4和asp.net core 2 web api做个练习项目(二), 这部分都是angular

    上一篇: http://www.cnblogs.com/cgzl/p/7755801.html 完成client.service.ts: import { Injectable } from '@an ...

  2. ASP.NET Core和Web API:用于管理异常和一致响应的自定义包装器

    目录 介绍 为什么? 怎么做? VMD.RESTApiResponseWrapper Nuget软件包 安装及使用 ASP.NET Core集成 ASP.NET Web API集成 样本响应输出 定义 ...

  3. C#编写ASP.NET Core的Web API并部署到IIS上的详细教程(API用于准确获取Word/Excel/PPT/PDF的页数)6 -将项目部署到IIS,及常见错误解决方案

    C#编写ASP.NET Core的Web API并部署到IIS上的详细教程(API用于准确获取Word/Excel/PPT/PDF的页数)6 -将项目部署到IIS,及常见错误解决方案 1.前言 2.安 ...

  4. ASP.NET Core 教学 - Web API JSON 序列化设定

    用 JSON 作为 Web API 资料传递格式,并使用 camelCase 作为名称命名规则,几乎已成为通用的标准.ASP.NET Core Web API 也很贴心的把回传物件格式预设为 JSON ...

  5. 什么是ASP.NET Core静态Web资产?

    What are ASP.NET Core Static Web Assets? HostBuilder.ConfigureWebHostDefaults()中发生了很多隐藏的魔术(最终称为Confi ...

  6. 2022年8月10日:使用 ASP.NET Core 为初学者构建 Web 应用程序--使用 ASP.NET Core 创建 Web UI(没看懂需要再看一遍)

    ASP.NET Core 支持使用名为 Razor 的本地模板化引擎创建网页. 本模块介绍了如何使用 Razor 和 ASP.NET Core 创建网页. 简介 通过在首选终端中运行以下命令,确保已安 ...

  7. asp编程工具_使用ASP.NET Core构建RESTful API的技术指南

    译者荐语:利用周末的时间,本人拜读了长沙.NET技术社区翻译的技术文章<微软RESTFul API指南>,打算按照步骤写一个完整的教程,后来无意中看到了这篇文章,与我要写的主题有不少相似之 ...

  8. Asp Net Core 5 REST API 使用 RefreshToken 刷新 JWT - Step by Step(三)

    翻译自 Mohamad Lawand 2021年1月25日的文章 <Refresh JWT with Refresh Tokens in Asp Net Core 5 Rest API Step ...

  9. Asp.Net Core 5 REST API 使用 JWT 身份验证 - Step by Step(二)

    翻译自 Mohamad Lawand 2021年1月22日的文章 <Asp Net Core 5 Rest API Authentication with JWT Step by Step> ...

最新文章

  1. 如何轻松实现iOS9多任务管理器效果(iCarousel高级教程)
  2. 当莎士比亚遇见Google Flax:教你用​字符级语言模型和归递神经网络写“莎士比亚”式句子...
  3. linux之文件基本操作学习笔记
  4. web.config文件
  5. vlan的基本指令_10、Vlan的基本常用命令
  6. php v9 分页静态,PHPCMS V9自定义栏目伪静态实现方法(列表页/分页/内容页)
  7. JavaWeb(十)——jetty服务器、创建jsp项目、servlet生命周期及url的匹配规则
  8. java8 函数式编程_Java 8函数式编程:延迟实例化
  9. get占位符传多个参数_mybatis多个参数(不使用@param注解情况下),sql参数占位符正确写法...
  10. 【渝粤题库】广东开放大学 文化服务营销管理 形成性考核
  11. 小车故障灯亮显示大全_史上最全汽车故障灯大全,留着一定有用!
  12. linux 与win共享文件夹
  13. windows10pygame下载安装问题描述
  14. 2019华为杯研究生数学建模竞赛总结(E题 国一)
  15. koreader下载_Koreader阅读器app免费安装最新版|Koreader阅读器2018手机最新版下载_v1.0_9ht安卓下载...
  16. 手机搭建php环境,安卓手机搭建PHP环境教程
  17. 一步一步分析Gin框架路由源码及radix tree基数树
  18. arduino IED2.0实现Serial.println打印结果
  19. limited扫描仪 pfu_扫描一气呵成:PFU新款扫描仪赏析
  20. EasyPusher安卓Android手机直播推送之MediaCodec 硬编码H264格式

热门文章

  1. [技术] 谈谈编程思想
  2. linux系统下文件查找
  3. [转]sqlserver 创建分区表
  4. Chapter 3 - 作用域
  5. ctypes 使用方法与说明
  6. c++ ANSI、UNICODE、UTF8互转
  7. cmake笔记(1)
  8. Mac OSX上安装Python的方法
  9. ios底部栏设计规范_2016年全新Apple iOS设计规范指南!
  10. python colorbar位置大小调整_python - matplotlib相邻子图:添加colorbar更改子图的大小 - 堆栈内存溢出...