[关闭]
@carlchen 2017-04-27T05:54:38.000000Z 字数 13502 阅读 625

第五章:多用户版本的待办事项应用

前端Angular2教程

第四章我们完成的Todo的基本功能看起来还不错,但是有个大问题,就是每个用户看到的都是一样的待办事项,我们希望的是每个用户拥有自己的待办事项列表。

我们来分析一下怎么做,如果每个todo对象带一个UserId属性是不是可以解决呢?好像可以,逻辑大概是这样:用户登录后转到/todo,TodoComponent得到当前用户的UserId,然后调用TodoService中的方法,传入当前用户的UserId,TodoService中按UserId去筛选当前用户的Todos。
但可惜我们目前的LoginComponent还是个实验品,很多功能的缺失,我们是先去做Login呢,还是利用现有的Todo对象先试验一下呢?我个人的习惯是先进行试验。

数据驱动开发

按之前我们分析的,给todo加一个userId属性,我们手动给我们目前的数据加上userId属性吧。更改todo\todo-data.json为下面的样子:

  1. {
  2. "todos": [
  3. {
  4. "id": "bf75769b-4810-64e9-d154-418ff2dbf55e",
  5. "desc": "getting up",
  6. "completed": false,
  7. "userId": 1
  8. },
  9. {
  10. "id": "5894a12f-dae1-5ab0-5761-1371ba4f703e",
  11. "desc": "have breakfast",
  12. "completed": true,
  13. "userId": 2
  14. },
  15. {
  16. "id": "0d2596c4-216b-df3d-1608-633899c5a549",
  17. "desc": "go to school",
  18. "completed": true,
  19. "userId": 1
  20. },
  21. {
  22. "id": "0b1f6614-1def-3346-f070-d6d39c02d6b7",
  23. "desc": "test",
  24. "completed": false,
  25. "userId": 2
  26. },
  27. {
  28. "id": "c1e02a43-6364-5515-1652-a772f0fab7b3",
  29. "desc": "This is a te",
  30. "completed": false,
  31. "userId": 1
  32. }
  33. ]
  34. }

如果你还没有启动json-server的话让我们启动它: json-server ./src/app/todo/todo-data.json,然后打开浏览器在地址栏输入http://localhost:3000/todos/?userId=2你会看到只有userId=2的json被输出了

  1. [
  2. {
  3. "id": "5894a12f-dae1-5ab0-5761-1371ba4f703e",
  4. "desc": "have breakfast",
  5. "completed": true,
  6. "userId": 2
  7. },
  8. {
  9. "id": "0b1f6614-1def-3346-f070-d6d39c02d6b7",
  10. "desc": "test",
  11. "completed": false,
  12. "userId": 2
  13. }
  14. ]

有兴趣的话可以再试试http://localhost:3000/todos/?userId=2&completed=false或其他组合查询。现在todo有了userId字段,但我们还没有User对象,User的json表现形式看起来应该是这样:

  1. {
  2. "id": 1,
  3. "username": "wang",
  4. "password": "1234"
  5. }

当然这个表现形式有很多问题,比如密码是明文的,这些问题我们先不管,但大概样子是类似的。那么现在如果要建立User数据库的话,我们应该新建一个user-data.json

  1. {
  2. "users": [
  3. {
  4. "id": 1,
  5. "username": "wang",
  6. "password": "1234"
  7. },
  8. {
  9. "id": 2,
  10. "username": "peng",
  11. "password": "5678"
  12. }
  13. ]
  14. }

但这样做的话感觉单独为其建一个文件有点不值得,我们干脆把user和todo数据都放在一个文件吧,现在删除./src/app/todo/todo-data.json删除,在src\app下面新建一个data.json

  1. {
  2. "todos": [
  3. {
  4. "id": "bf75769b-4810-64e9-d154-418ff2dbf55e",
  5. "desc": "getting up",
  6. "completed": false,
  7. "userId": 1
  8. },
  9. {
  10. "id": "5894a12f-dae1-5ab0-5761-1371ba4f703e",
  11. "desc": "have breakfast",
  12. "completed": true,
  13. "userId": 2
  14. },
  15. {
  16. "id": "0d2596c4-216b-df3d-1608-633899c5a549",
  17. "desc": "go to school",
  18. "completed": true,
  19. "userId": 1
  20. },
  21. {
  22. "id": "0b1f6614-1def-3346-f070-d6d39c02d6b7",
  23. "desc": "test",
  24. "completed": false,
  25. "userId": 2
  26. },
  27. {
  28. "id": "c1e02a43-6364-5515-1652-a772f0fab7b3",
  29. "desc": "This is a te",
  30. "completed": false,
  31. "userId": 1
  32. }
  33. ],
  34. "users": [
  35. {
  36. "id": 1,
  37. "username": "wang",
  38. "password": "1234"
  39. },
  40. {
  41. "id": 2,
  42. "username": "peng",
  43. "password": "5678"
  44. }
  45. ]
  46. }

当然有了数据,我们就得有对应的对象,基于同样的理由,我们把所有的entity对象都放在一个文件:删除src\app\todo\todo.model.ts,在src\app下新建一个目录domain,然后在domain下新建一个entities.ts,请别忘了更新所有的引用。

  1. export class Todo {
  2. id: string;
  3. desc: string;
  4. completed: boolean;
  5. userId: number;
  6. }
  7. export class User {
  8. id: number;
  9. username: string;
  10. password: string;
  11. }

对于TodoService来说,我们可以做的就是按照刚才的逻辑进行改写:删除和切换状态的逻辑不用改,因为是用Todo的ID标识的。其他的要在访问的URL中加入userId的参数。添加用户的时候要把userId传入:

  1. ...
  2. addTodo(desc:string): Promise<Todo> {
  3. let todo = {
  4. id: UUID.UUID(),
  5. desc: desc,
  6. completed: false,
  7. userId: this.userId
  8. };
  9. return this.http
  10. .post(this.api_url, JSON.stringify(todo), {headers: this.headers})
  11. .toPromise()
  12. .then(res => res.json() as Todo)
  13. .catch(this.handleError);
  14. }
  15. getTodos(): Promise<Todo[]>{
  16. return this.http.get(`${this.api_url}?userId=${this.userId}`)
  17. .toPromise()
  18. .then(res => res.json() as Todo[])
  19. .catch(this.handleError);
  20. }
  21. filterTodos(filter: string): Promise<Todo[]> {
  22. switch(filter){
  23. case 'ACTIVE': return this.http
  24. .get(`${this.api_url}?completed=false&userId=${this.userId}`)
  25. .toPromise()
  26. .then(res => res.json() as Todo[])
  27. .catch(this.handleError);
  28. case 'COMPLETED': return this.http
  29. .get(`${this.api_url}?completed=true&userId=${this.userId}`)
  30. .toPromise()
  31. .then(res => res.json() as Todo[])
  32. .catch(this.handleError);
  33. default:
  34. return this.getTodos();
  35. }
  36. }
  37. ...

验证用户账户的流程

我们来梳理一下用户验证的流程

  1. 存储要访问的URL
  2. 根据本地的已登录标识判断是否此用户已经登录,如果已登录就直接放行
  3. 如果未登录导航到登录页面 用户填写用户名和密码进行登录
  4. 系统根据用户名查找用户表中是否存在此用户,如果不存在此用户,返回错误
  5. 如果存在对比填写的密码和存储的密码是否一致,如果不一致,返回错误
  6. 如果一致,存储此用户的已登录标识到本地
  7. 导航到原本要访问的URL即第一步中存储的URL,删掉本地存储的URL

看上去我们需要实现

核心模块

根据这个逻辑流程,我们来组织一下代码。开始之前我们想把认证相关的代码组织在一个新的模块下,我们暂时叫它core吧。在src\app下新建一个core目录,然后在core下面新建一个core.module.ts

  1. import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. @NgModule({
  4. imports: [
  5. CommonModule
  6. ]
  7. })
  8. export class CoreModule {
  9. constructor (@Optional() @SkipSelf() parentModule: CoreModule) {
  10. if (parentModule) {
  11. throw new Error(
  12. 'CoreModule is already loaded. Import it in the AppModule only');
  13. }
  14. }

注意到这个模块和其他模块不太一样,原因是我们希望只在应用启动时导入它一次,而不会在其它地方导入它。在模块的构造函数中我们会要求Angular把CoreModule注入自身,这看起来像一个危险的循环注入。不过,@SkipSelf装饰器意味着在当前注入器的所有祖先注入器中寻找CoreModule。如果该构造函数在我们所期望的AppModule中运行,就没有任何祖先注入器能够提供CoreModule的实例,于是注入器会放弃查找。默认情况下,当注入器找不到想找的提供商时,会抛出一个错误。但@Optional装饰器表示找不到该服务也无所谓。 于是注入器会返回null,parentModule参数也就被赋成了空值,而构造函数没有任何异常。

那么我们在什么时候会需要这样一个模块?比如在这个模块中我们可能会要提供用户服务(UserService),这样的服务系统各个地方都需要,但我们不希望它被创建多次,希望它是一个单例。再比如某些只应用于AppComponent模板的一次性组件,没有必要共享它们,然而如果把它们留在根目录,还是显得太乱了。我们可以通过这种形式隐藏它们的实现细节。然后通过根模块AppModule导入CoreModule来获取其能力。

路由守卫

首先我们来看看Angular内建的路由守卫机制,在实际工作中我们常常会碰到下列需求:

我们可以往路由配置中添加守卫,来处理这些场景。守卫返回true,导航过程会继续;返回false,导航过程会终止,且用户会留在原地(守卫还可以告诉路由器导航到别处,这样也取消当前的导航)。

路由器支持多种守卫:

在分层路由的每个级别上,我们都可以设置多个守卫。路由器会先按照从最深的子路由由下往上检查的顺序来检查CanDeactivate守护条件。然后它会按照从上到下的顺序检查CanActivate守卫。如果任何守卫返回false,其它尚未完成的守卫会被取消,这样整个导航就被取消了。

本例中我们希望用户未登录前不能访问todo,那么需要使用CanActivate

  1. import { AuthGuardService } from '../core/auth-guard.service';
  2. const routes: Routes = [
  3. {
  4. path: 'todo/:filter',
  5. canActivate: [AuthGuardService],
  6. component: TodoComponent
  7. }
  8. ];

当然光这么写是没有用的,下面我们来建立一个AuthGuardService,命令行中键入ng g s core/auth-guard(angular-cli对于Camel写法的文件名是采用-来分隔每个大写的词)。

  1. import { Injectable, Inject } from '@angular/core';
  2. import {
  3. CanActivate,
  4. Router,
  5. ActivatedRouteSnapshot,
  6. RouterStateSnapshot } from '@angular/router';
  7. @Injectable()
  8. export class AuthGuardService implements CanActivate {
  9. constructor(private router: Router) { }
  10. canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
  11. //取得用户访问的URL
  12. let url: string = state.url;
  13. return this.checkLogin(url);
  14. }
  15. checkLogin(url: string): boolean {
  16. //如果用户已经登录就放行
  17. if (localStorage.getItem('userId') !== null) { return true; }
  18. //否则,存储要访问的URl到本地
  19. localStorage.setItem('redirectUrl', url);
  20. //然后导航到登陆页面
  21. this.router.navigate(['/login']);
  22. //返回false,取消导航
  23. return false;
  24. }
  25. }

观察上面代码,我们发现本地存储的userId的存在与否决定了用户是否已登录的状态,这当然是一个漏洞百出的实现,但我们暂且不去管它。现在我们要在登录时把这个状态值写进去。我们新建一个登录鉴权的AuthServiceng g s core/auth

  1. import { Injectable, Inject } from '@angular/core';
  2. import { Http, Headers, Response } from '@angular/http';
  3. import 'rxjs/add/operator/toPromise';
  4. import { Auth } from '../domain/entities';
  5. @Injectable()
  6. export class AuthService {
  7. constructor(private http: Http, @Inject('user') private userService) { }
  8. loginWithCredentials(username: string, password: string): Promise<Auth> {
  9. return this.userService
  10. .findUser(username)
  11. .then(user => {
  12. let auth = new Auth();
  13. localStorage.removeItem('userId');
  14. let redirectUrl = (localStorage.getItem('redirectUrl') === null)?
  15. '/': localStorage.getItem('redirectUrl');
  16. auth.redirectUrl = redirectUrl;
  17. if (null === user){
  18. auth.hasError = true;
  19. auth.errMsg = 'user not found';
  20. } else if (password === user.password) {
  21. auth.user = Object.assign({}, user);
  22. auth.hasError = false;
  23. localStorage.setItem('userId',user.id);
  24. } else {
  25. auth.hasError = true;
  26. auth.errMsg = 'password not match';
  27. }
  28. return auth;
  29. })
  30. .catch(this.handleError);
  31. }
  32. private handleError(error: any): Promise<any> {
  33. console.error('An error occurred', error); // for demo purposes only
  34. return Promise.reject(error.message || error);
  35. }
  36. }

注意到我们返回了一个Auth对象,这是因为我们要知道几件事:

这个Auth对象同样在src\app\domain\entities.ts中声明

  1. export class Auth {
  2. user: User;
  3. hasError: boolean;
  4. errMsg: string;
  5. redirectUrl: string;
  6. }

当然我们还得实现UserService:ng g s user

  1. import { Injectable } from '@angular/core';
  2. import { Http, Headers, Response } from '@angular/http';
  3. import 'rxjs/add/operator/toPromise';
  4. import { User } from '../domain/entities';
  5. @Injectable()
  6. export class UserService {
  7. private api_url = 'http://localhost:3000/users';
  8. constructor(private http: Http) { }
  9. findUser(username: string): Promise<User> {
  10. const url = `${this.api_url}/?username=${username}`;
  11. return this.http.get(url)
  12. .toPromise()
  13. .then(res => {
  14. let users = res.json() as User[];
  15. return (users.length>0)?users[0]:null;
  16. })
  17. .catch(this.handleError);
  18. }
  19. private handleError(error: any): Promise<any> {
  20. console.error('An error occurred', error); // for demo purposes only
  21. return Promise.reject(error.message || error);
  22. }
  23. }

这段代码比较简单,就不细讲了。下面我们改造一下src\app\login\login.component.html,在原来用户名的验证信息下加入,用于显示用户不存在或者密码不对的情况

  1. <div *ngIf="usernameRef.errors?.required">this is required</div>
  2. <div *ngIf="usernameRef.errors?.minlength">should be at least 3 charactors</div>
  3. <!--add the code below-->
  4. <div *ngIf="auth?.hasError">{{auth.errMsg}}</div>

接下来我们还得改造src\app\login\login.component.ts

  1. import { Component, OnInit, Inject } from '@angular/core';
  2. import { Router, ActivatedRoute, Params } from '@angular/router';
  3. import { Auth } from '../domain/entities';
  4. @Component({
  5. selector: 'app-login',
  6. templateUrl: './login.component.html',
  7. styleUrls: ['./login.component.css']
  8. })
  9. export class LoginComponent implements OnInit {
  10. username = '';
  11. password = '';
  12. auth: Auth;
  13. constructor(@Inject('auth') private service, private router: Router) { }
  14. ngOnInit() {
  15. }
  16. onSubmit(formValue){
  17. this.service
  18. .loginWithCredentials(formValue.login.username, formValue.login.password)
  19. .then(auth => {
  20. let redirectUrl = (auth.redirectUrl === null)? '/': auth.redirectUrl;
  21. if(!auth.hasError){
  22. this.router.navigate([redirectUrl]);
  23. localStorage.removeItem('redirectUrl');
  24. } else {
  25. this.auth = Object.assign({}, auth);
  26. }
  27. });
  28. }
  29. }

然后我们别忘了在core模块中声明我们的服务src\app\core\core.module.ts

  1. import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. import { AuthService } from './auth.service';
  4. import { UserService } from './user.service';
  5. import { AuthGuardService } from './auth-guard.service';
  6. @NgModule({
  7. imports: [
  8. CommonModule
  9. ],
  10. providers: [
  11. { provide: 'auth', useClass: AuthService },
  12. { provide: 'user', useClass: UserService },
  13. AuthGuardService
  14. ]
  15. })
  16. export class CoreModule {
  17. constructor (@Optional() @SkipSelf() parentModule: CoreModule) {
  18. if (parentModule) {
  19. throw new Error(
  20. 'CoreModule is already loaded. Import it in the AppModule only');
  21. }
  22. }
  23. }

最后我们得改写一下TodoService,因为我们访问的URL变了,要传递的数据也有些变化

  1. //todo.service.ts代码片段
  2. // POST /todos
  3. addTodo(desc:string): Promise<Todo> {
  4. //“+”是一个简易方法可以把string转成number
  5. const userId:number = +localStorage.getItem('userId');
  6. let todo = {
  7. id: UUID.UUID(),
  8. desc: desc,
  9. completed: false,
  10. userId
  11. };
  12. return this.http
  13. .post(this.api_url, JSON.stringify(todo), {headers: this.headers})
  14. .toPromise()
  15. .then(res => res.json() as Todo)
  16. .catch(this.handleError);
  17. }
  18. // GET /todos
  19. getTodos(): Promise<Todo[]>{
  20. const userId = +localStorage.getItem('userId');
  21. const url = `${this.api_url}/?userId=${userId}`;
  22. return this.http.get(url)
  23. .toPromise()
  24. .then(res => res.json() as Todo[])
  25. .catch(this.handleError);
  26. }
  27. // GET /todos?completed=true/false
  28. filterTodos(filter: string): Promise<Todo[]> {
  29. const userId:number = +localStorage.getItem('userId');
  30. const url = `${this.api_url}/?userId=${userId}`;
  31. switch(filter){
  32. case 'ACTIVE': return this.http
  33. .get(`${url}&completed=false`)
  34. .toPromise()
  35. .then(res => res.json() as Todo[])
  36. .catch(this.handleError);
  37. case 'COMPLETED': return this.http
  38. .get(`${url}&completed=true`)
  39. .toPromise()
  40. .then(res => res.json() as Todo[])
  41. .catch(this.handleError);
  42. default:
  43. return this.getTodos();
  44. }
  45. }

现在应该已经ok了,我们来看看效果:
用户密码不匹配时,显示password not match

用户密码不匹配时提示

用户不存在时,显示user not found

用户不存在的提示

直接在浏览器地址栏输入http://localhost:4200/todo,你会发现被重新导航到了login。输入正确的用户名密码后,我们被导航到了todo,现在每个用户都可以创建属于自己的待办事项了。

image_1b23hdv51l621elh1uucsri32213.png-51.1kB

路由模块化

Angular团队推荐把路由模块化,这样便于使业务逻辑和路由松耦合。虽然目前在我们的应用中感觉用处不大,但按官方推荐的方式还是和大家一起改造一下吧。删掉原有的app.routes.tstodo.routes.ts。添加app-routing.module.ts:

  1. import { NgModule } from '@angular/core';
  2. import { Routes, RouterModule } from '@angular/router';
  3. import { LoginComponent } from './login/login.component';
  4. const routes: Routes = [
  5. {
  6. path: '',
  7. redirectTo: 'login',
  8. pathMatch: 'full'
  9. },
  10. {
  11. path: 'login',
  12. component: LoginComponent
  13. },
  14. {
  15. path: 'todo',
  16. redirectTo: 'todo/ALL'
  17. }
  18. ];
  19. @NgModule({
  20. imports: [
  21. RouterModule.forRoot(routes)
  22. ],
  23. exports: [
  24. RouterModule
  25. ]
  26. })
  27. export class AppRoutingModule {}

以及src\app\todo\todo-routing.module.ts

  1. import { NgModule } from '@angular/core';
  2. import { Routes, RouterModule } from '@angular/router';
  3. import { TodoComponent } from './todo.component';
  4. import { AuthGuardService } from '../core/auth-guard.service';
  5. const routes: Routes = [
  6. {
  7. path: 'todo/:filter',
  8. canActivate: [AuthGuardService],
  9. component: TodoComponent
  10. }
  11. ];
  12. @NgModule({
  13. imports: [ RouterModule.forChild(routes) ],
  14. exports: [ RouterModule ]
  15. })
  16. export class TodoRoutingModule { }

并分别在AppModule和TodoModule中引入路由模块。

用VSCode进行调试

我们一直都没讲如何用vscode进行debug,这章我们来介绍一下。首先需要安装一个vscode插件,点击左侧最下面的图标或者“在查看菜单中选择命令面板,输入install,选择扩展:安装扩展”,然后输入“debugger for chrome”回车,点击安装即可。

VS Code Chome 调试插件

然后点击最左边的倒数第二个按钮

debug profile创建

如果是第一次使用的话,齿轮图标上会有个红点,点击选择debugger for chrome,vscode会帮你创建一个配置文件,这个文件位于\.vscode\launch.json是debugger的配置文件,请改写成下面的样子。注意如果是MacOSX或者Linux,请把userDataDir替换成对应的临时目录,另外把"webpack:///C:*":"C:/*"替换成"webpack:///*": "/*",这句是因为angular-cli是采用webpack打包的,如果没有使用angular-cli不需要添加这句。

  1. {
  2. "version": "0.2.0",
  3. "configurations": [
  4. {
  5. "name": "Launch Chrome against localhost, with sourcemaps",
  6. "type": "chrome",
  7. "request": "launch",
  8. "url": "http://localhost:4200",
  9. "sourceMaps": true,
  10. "runtimeArgs": [
  11. "--disable-session-crashed-bubble",
  12. "--disable-infobars"
  13. ],
  14. "diagnosticLogging": true,
  15. "webRoot": "${workspaceRoot}/src",
  16. //windows setup
  17. "userDataDir": "C:\\temp\\chromeDummyDir",
  18. "sourceMapPathOverrides": {
  19. "webpack:///C:*":"C:/*"
  20. //use "webpack:///*": "/*" on Linux/OSX
  21. }
  22. },
  23. {
  24. "name": "Attach to Chrome, with sourcemaps",
  25. "type": "chrome",
  26. "request": "attach",
  27. "port": 9222,
  28. "sourceMaps": true,
  29. "diagnosticLogging": true,
  30. "webRoot": "${workspaceRoot}/src",
  31. "sourceMapPathOverrides": {
  32. "webpack:///C:*":"C:/*"
  33. }
  34. }
  35. ]
  36. }

现在你可以试着在源码中设置一个断点,点击debug视图中的debug按钮,可以尝试右键点击变量把它放到监视中看看变量值或者逐步调试应用。

在VSCODE中 Debug

在笔者写书的时间点,由于一些问题(可能是zone.js引起的异常),启动VSCode debug时可能会自动进入一个断点,只要点击继续就可以了,并不影响调试。

可能由于Angular的zone.js引起的异常

本章完整代码见: https://github.com/wpcfan/awesome-tutorials/tree/chap05/angular2/ng2-tut


添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注