Angular2端
創建View Model
在wwwroot/app下創建一個目錄:_model, 並添加一個Typescript文件RequestResult.ts,內容應該是這樣。
export class RequestResult {
State: number;
Msg: string;
Data: Object;
}
創建Service
在wwwroot/app下創建一個目錄:_services,並添加一個Typescript文件auth.service.ts,內容應該是這樣。
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中
創建Component
在wwwroot/app下創建一個目錄home,該目錄用來存放HomeComponent,home應擁有如下文件:
-
home.component.ts
import { Component, OnInit } from "@angular/core"; import { AuthService } from "../_services/auth.service"; @Component({ moduleId: module.id, selector: "my-home", templateUrl: "view.html", styleUrls: ["style.css"] }) 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
/*styles of this view*/
本例中沒有添加任何樣式,如有需要可以寫在這里。
-
view.html
<div *ngIf="isLogin"> <h1>Hi <span>{{userName}}</span></h1> </div> <div *ngIf="!isLogin"> <h1>please login</h1> <a routerLink="/login">Login</a> </div>*ngIf=""是Angular2 的其中一種標記語法,作用是當返回真時渲染該節點,完整教程請參閱官方文檔。
在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
/*styles of this view*/
-
view.html
<table> <tr> <td>userName:</td> <td><input [(ngModel)]="userName" placeholder="useName:try type user1" /></td> </tr> <tr> <td>userName:</td> <td><input [(ngModel)]="password" placeholder="password:try type user1psd" /></td> </tr> <tr> <td></td> <td><input type="button" (click)="login()" value="Login" /></td> </tr> </table>
應用路由
路由是切換多頁面用的。
在wwwroot/app下新建一個Typescript文件,命名為app-routing.module.ts,內容應該是這個樣子。
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { HomeComponent } from "./home/home.component";
import { LoginComponent } from "./login/login.component"
const routes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", component: HomeComponent },
{ path: "login", component: LoginComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
接下來我們來應用這個路由,
打開app.module.ts,更新代碼如下:
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { HttpModule } from "@angular/http";
import { FormsModule } from "@angular/forms";
import { AppRoutingModule } from "./app-routing.module";
import { AuthService } from "./_services/auth.service";
import { AppComponent } from "./app.component";
import { HomeComponent } from "./home/home.component";
import { LoginComponent } from "./login/login.component";
@NgModule({
bootstrap: [AppComponent],
imports: [
BrowserModule,
HttpModule,
AppRoutingModule,
FormsModule
],
declarations: [
AppComponent,
HomeComponent,
LoginComponent
],
providers: [AuthService]
})
export class AppModule { }
NgModule和BrowserModule你可以理解為基礎模塊,必加的。
HttpModule是做http請求用的。
FormsModule是做雙向數據綁定用的,比如下面這樣的,如果想把數據從view更新到component,就必須加這個。
<input [(ngModel)]="userName" placeholder="useName:try type user1" />
AppRoutingModule即為我們剛才添加的路由文件。
AuthService是我們最早添加的service文件。
AppComponent是我們最初添加的那個app.component.ts里的那個component.
HomeComponent,LoginComponent同上。
最后我們再app.component.ts中添加路由錨點,
把template的值為 "<router-outlet></router-outlet>"
完整的代碼應該是這樣:
import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'my-app',
template: "<router-outlet></router-outlet>",
})
export class AppComponent {
}
router-outlet是路由錨點的關鍵詞。

