之前用过dva、umi等前端框架/库,对路由有一定的了解,所以学起来还好。
1 基础
页面就是路由。
There are three main components that we use to configure routing in Angular:
首先搞了about、contact、home三个component
然后在app.module.ts中定义好路由:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
import { HomeComponent } from './home/home.component';
// routing goes here
import {
RouterModule,
Routes
} from '@angular/router';
const routes: Routes = [
// basic routes
{path: '', redirectTo: 'home', pathMatch: 'full'},
{path: 'home', component: HomeComponent},
{path: 'about', component: AboutComponent},
{path: 'contact', component: ContactComponent},
{path: 'contactus', redirectTo: 'contact'},
];
@NgModule({
declarations: [
AppComponent,
AboutComponent,
ContactComponent,
HomeComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
RouterModule.forRoot(routes), // install our routes
],
providers: [
// uncomment this for "hash-bang" routing
// 意思就是注释掉以后就不是hash based routing了,那个#就没了
{provide: LocationStrategy, useClass: HashLocationStrategy},
{provide: APP_BASE_HREF, useValue: '/'},
],
bootstrap: [AppComponent]
})
export class AppModule { }
这里还要学习一下两种不同的路由策略,一种是HashLocationStrategy,还有一种是PathLocationStrategy:
{provide: LocationStrategy, useClass: PathLocationStrategy},
也即是所谓的HTML5 routing strategy,最明显的区别就是没有那个#了。。。。
在app.component.html中:
Router Sample
这里有两个重要的东西,一个是[routerLink],用来表示路由链接,另一个是
2 路由参数和嵌套路由
可以考虑把要嵌套的部分当成一个子模块,比如数理的products.module.ts,然后在app.module.ts中去使用:
const routes: Routes = [
// basic routes
{path: '', redirectTo: 'home', pathMatch: 'full'},
{path: 'home', component: HomeComponent},
{path: 'about', component: AboutComponent},
{path: 'contact', component: ContactComponent},
{path: 'contactus', redirectTo: 'contact'},
// nested
{
path: 'products',
component: ProductsComponent,
children: childRoutes
}
];
路由参数加一个冒号:就好了,比如在products.module.ts中:
export const routes: Routes = [
{ path: '', redirectTo: 'main', pathMatch: 'full' },
{ path: 'main', component: MainComponent },
{ path: 'more-info', component: MoreInfoComponent },
{ path: ':id', component: ProductComponent },
];
products.component.html:
Products
在product.component.ts中:
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
id: string;
constructor(private route: ActivatedRoute) {
route.params.subscribe(params => {
// const idx = 'id';
// this.id = params[idx];
// please configure tslint.json to enable object access via string literal
// in rules: {} add "no-string-literal": false,
this.id = params['id'];
});
}
ngOnInit() {
}
}
3 登陆和验证
首先写一个用来验证的service,auth.service.ts:
import { Injectable } from '@angular/core';
@Injectable()
export class AuthService {
login(user: string, password: string): boolean {
if (user === 'user' && password === 'password') {
localStorage.setItem('username', user);
return true;
}
return false;
}
logout(): any {
localStorage.removeItem('username');
}
getUser(): any {
return localStorage.getItem('username');
}
isLoggedIn(): boolean {
return this.getUser() !== null;
}
}
export const AUTH_PROVIDERS: Array = [
{ provide: AuthService, useClass: AuthService }
];
还有logged-in.guard.ts:
/* tslint:disble max-line-length */
import { Injectable } from '@angular/core';
import {
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot
} from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
@Injectable()
export class LoggedInGuard implements CanActivate {
constructor(private authService: AuthService) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable | Promise | boolean {
const isLoggedIn = this.authService.isLoggedIn();
console.log('canActivate', isLoggedIn);
return isLoggedIn;
}
}
然后写login和protected两个component,效果是输入user和password后可以登录,登陆以后可以看到protected的页面,这里就不贴代码了。
这个部分书里还是写得简单了,没有和后端结合起来,只是展示了一下验证的流程,读完还是云里雾里。要把前后端的验证都做一遍才知道深浅啊。