import { Injectable } from "@angular/core"; import { Headers, Http } from "@angular/http"; import "rxjs/add/operator/toPromise"; import { RequestResult } from "../_model/RequestResult"; @Injectable() export class AuthService { private tokeyKey = "token"; private token: string; constructor( private http: Http ) { } login(userName: string, password: string): Promise<RequestResult> { return this.http.post("/api/TokenAuth", { Username: userName, Password: password }).toPromise() .then(response => { let result = response.json() as RequestResult; if (result.State == 1) { let json = result.Data as any; sessionStorage.setItem("token", json.accessToken); } return result; }) .catch(this.handleError); } checkLogin(): boolean { var token = sessionStorage.getItem(this.tokeyKey); return token != null; } getUserInfo(): Promise<RequestResult> { return this.authGet("/api/TokenAuth"); } authPost(url: string, body: any): Promise<RequestResult> { let headers = this.initAuthHeaders(); return this.http.post(url, body, { headers: headers }).toPromise() .then(response => response.json() as RequestResult) .catch(this.handleError); } authGet(url): Promise<RequestResult> { let headers = this.initAuthHeaders(); return this.http.get(url, { headers: headers }).toPromise() .then(response => response.json() as RequestResult) .catch(this.handleError); } private getLocalToken(): string { if (!this.token) { this.token = sessionStorage.getItem(this.tokeyKey); } return this.token; } private initAuthHeaders(): Headers { let token = this.getLocalToken(); if (token == null) throw "No token"; var headers = new Headers(); headers.append("Authorization", "Bearer " + token); return headers; } private handleError(error: any): Promise<any> { console.error('An error occurred', error); return Promise.reject(error.message || error); } }
本文件主要用来完成登录以及登录验证工作,之后该service将可以被注入到Component中以便被Component调用。
注:主要的逻辑都应该写到service中
4.2.3.创建Component4.2.3.1.在wwwroot/app下创建一个目录home,该目录用来存放HomeComponent,home应拥有如下文件:
home.component.ts
import { Component, OnInit } ; import { AuthService } ; @Component({ moduleId: module.id, selector: , templateUrl: , styleUrls: [] }) export class HomeComponent implements OnInit { isLogin = false; userName: string; constructor( private authService: AuthService ) { } ngOnInit(): void { this.isLogin = this.authService.checkLogin(); if (this.isLogin) { this.authService.getUserInfo().then(res => { this.userName = (res.Data as any).UserName; }); } } }
查阅代码,在@Component中指定了View以及style。
AuthService被在构造方法中被注入了本Component,ngOnInit是接口OnInit的一个方法,他在Component初始化时会被调用。
style.css
本例中没有添加任何样式,如有需要可以写在这里。
view.html
Hi {{userName}}please loginLogin
*ngIf=""是Angular2 的其中一种标记语法,作用是当返回真时渲染该节点,完整教程请参阅官方文档。
4.2.3.2.在wwwroot/app下创建目录Login,该目录用来存放LoginComponent,文件结构类似于上一节。
login.component.ts
import { Component } from "@angular/core"; import { Router } from '@angular/router'; import { AuthService } from "../_services/auth.service"; @Component({ moduleId: module.id, selector: "my-login", templateUrl: "view.html", styleUrls: ["style.css"] }) export class LoginComponent { private userName: string; private password: string; constructor( private authService: AuthService, private router: Router ) { } login() { this.authService.login(this.userName, this.password) .then(result => { if (result.State == 1) { this.router.navigate(["./home"]); } else { alert(result.Msg); } }); } }
style.css
view.html
userName:userName:
路由是切换多页面用的。
在wwwroot/app下新建一个Typescript文件,命名为app-routing.module.ts,内容应该是这个样子。