<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>
4.2.4.应用路由
路由是切换多页面用的。
在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是路由锚点的关键词。
至此,所有代码完成,F5调试吧。