Angular2 - Starter - Routes, Route Resolver
在基于Angualr的SPA中,路由是一个很重要的部分,它帮助我们更方便的实现页面上区域的内容的动态加载,不同tab的切换,同时及时更新浏览器地址栏的URN,使浏览器回退和前进能导航到历史访问的页面。
(1) 基本配置
1.1.配置base href
在配置RoutesModule之前,我们需要再index.html里配置base href,这样,每一个路由的路径的前缀都是base href,应用的图片,文件夹,样式等资源都通过该base href来定位。
//index.html
<base href='/'></base>
1.2.配置应用路由
//app.routes.ts
export const ROUTES: Routes = [
//根路径,通过base url:127.0.0.1:8888访问LogOnComponent,
{ path: '', component: LogOnComponent },
{ path: 'chats', component: ChatsComponent },
{ path: 'logon', component: LogOnComponent },
{ path: 'fresh', component: FreshComponent },
/*base url下的路由,如果在初始化路由时使用hash:通过127.0.0.1:8888/#/friends访问
如果不使用hash,则通过127.0.0.1:8888/friends访问
*/
{ path: 'friends',component: FriendsComponent }, {
path: 'other',
//在访问127.0.0.1:8888/#/other时,再去加载一个模块,这就加快了应用初始化的速度
loadChildren: () => System.import('./components/sections/+detail')
.then((comp: any) => comp.default),
},
/*在跳转到任何一个路由之前会实例化该组件,若成功(找到目标路由),则跳转到目标路由
若失败,则跳转到 NoContentComponent ,我们可以将它理解为错误路由时需要跳转到的位置
*/
{ path: '**', component: NoContentComponent },
];
1.3.在应用模块中加载路由
//app.module.ts
import { ROUTES } from './app.routes';
import {RouterModule, NoPreloading} from '@angular/router';
@NgModule({
bootstrap: [ AppComponent ],
imports: [ /*使用RouterModule.forRoot方法将路由配置加载到base url,
useHash:true,则urn在浏览器显示为http://127.0.0.1:8083/#/friends
useHash:false,则urn在浏览器显示为http://127.0.0.1:8083/friends
但其实,angular路由跳转都不会刷新整个页面,而是动态加载各个模块
enableTracing:true,在浏览器的输出窗口输出当前跳转操作的详细信息,如:
NavigationEnd(id: 2, url: '/friends', urlAfterRedirects: '/friends'),
preloadingStrategy: NoPreloading,允许组件懒加载,当应用加载成功之后,加载器便监听懒加载的路由的访问事件,一旦访问就去加载对应组件或模块
*/ RouterModule.forRoot(ROUTES, { useHash: false,enableTracing:false, preloadingStrategy: NoPreloading })
]
})
(2) 子模块的路由
2.1 建立子模块
//detail.module.ts
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { DetailComponent } from './detail.component';
import { FeedbackComponent } from '../../parts/feedback';
import { FeedbackRoutingModule } from './routing/feedback-routing.module';
import {AboutComponent} from "../about/about.component";
//装饰一个NgModule
@NgModule({
declarations: [
//引入该子模块的组件
DetailComponent,
FeedbackComponent,
AboutComponent
],
imports: [
//此处导入CommonModule,而不是app.module中使用的BrowserModule,
//如果BrowserModule被导入,就会报如下错误,可见BrowserModule用于加载根模块,CommonModule用于在懒加载的模块中提供angular的基本指令
/*Error: BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.
*/
CommonModule,
FormsModule,
//导入路由模块
FeedbackRoutingModule
]
})
export default class OtherModule { }
2.2 建立子应用模块的路由模块
//detail-routing.module.ts
import { ROUTES } from './feedback-routing.routes';
@NgModule({
imports:[
//使用RouterModule.forChild加载子路由模块
RouterModule.forChild(ROUTES)
],
exports:[
//导出的DetailRoutingModule 中携带一个加载了ROUTES的RouterModule
RouterModule
],
providers:[
PeopleSvc,
//到如一些作为服务的提供商
MemberShipResolver
]
})
export class DetailRoutingModule{}
2.3 配置子模块内部的路由
//detail-routing.routes.ts
import { Routes } from '@angular/router';
import { FeedbackComponent } from '../../../../components/parts/feedback';
import { DetailComponent } from '../detail.component';
import { AboutComponent } from '../../about/about.component';
import { MemberShipResolver } from '../../../../services/membership-resolver.service';
export const ROUTES:Routes = [
{
//应用子模块路径
path:'',
data:{title:'Other'},
component:DetailComponent,
outlet:'primary',
resolve: {
pageInfo: MemberShipResolver
},
//子路由
children:[
{ path:'logon',redirectTo:'' },
{
path: 'feedback',
component: FeedbackComponent,
/*定义实例化FeedbackComponent时的数据,可通过当前的ActivatedRoute对象来访问到 this.route.data.getValue()
*/
data:{title:'User feedback'} ,
resolve: {
userInfoResult: MemberShipResolver
}
},
{
path:'about',
component:AboutComponent
}
]
}
];
(3) 路由分析器
Router Resolver其实是一个服务,在跳转到某个路由时,该service可获取到当前ActivatedRoute,获取其携带的data,这里可以提前去服务端获取一些数据,或者做一些数据转换之后再进行组件的实例化和渲染。比如,当用户将要跳转到应用的反馈页面填写反馈时,我们可以通过一个membership-resolver去检查是否为登录用户,如果不是,则跳转到登录页面,如果是则显示历史反馈和反馈填写表单入口。
3.1 建立membership-resolver
//membership-resolver.service.ts
import { Injectable } from '@angular/core';
import { FeedbackSvc } from './feedbackSvc';
import {Router, RouterStateSnapshot, ActivatedRouteSnapshot, Resolve} from "@angular/router";
import {ClientState} from "./client-state.service";
@Injectable()
export class MemberShipResolver implements Resolve<string>{
//clientState:ClientState 该服务提供当前登录用户的信息
constructor(private router: Router,private peopleSvc:PeopleSvc,private clientState:ClientState) { } //实现 Resolve接口的resolve方法
resolve(route:ActivatedRouteSnapshot,state:RouterStateSnapshot):Promise<string>{
let me = this;
let clientUser = this.clientState.get('user');
let prom = new Promise(function(resolve,reject){
//如果当前登录用户为null,则跳转到logon
if(clientUser === null){
me.router.navigate(['./logon']);
resolve(null);
}else{
//获取所有feedback
me.feedbackSvc.getAll().then((data)=>{
if(data !== null){
resolve(data);
}else{
resolve(null);
}
});
}
});
return prom;
}
}
3.2 制定分析器解析的数据标识
//feedback.routing.ts
{
path: 'feedback',
component: FeedbackComponent,
data:{title:'User feedback'} ,
resolve: {
//定义feedbackResult的分析器,该分析器异步返回的数据将添加到data下
feedbackResult: MemberShipResolver
}
}
3.3 监控分析器数据变化
//feedback.component.ts
import { Component } from '@angular/core';
import { FeedbackSvc } from './feedbackSvc';
import {Router, ActivatedRoute} from "@angular/router";
import {Feedback} from "../../../models/business/Feedback";
import {User} from "../../../models/business/User";
import {ClientState} from "../../../services/client-state.service";
@Component({
selector:'feedback',
templateUrl:'feedback.component.html',
styleUrls:[ 'feedback.component.css' ],
providers:[ FeedbackSvc ]
}) export class FeedbackComponent{
private allFeedback:Feedback[] = [];
constructor(public feedbackSvc:FeedbackSvc, private router: Router,private route:ActivatedRoute,private client:ClientState){ } ngOnInit() {
let _this = this;
//注册当前路由携带的数据的变化回调
this.route.data.subscribe((data:Feedback[]) => {
if(data !== null){
//将分析器返回的数据作为component的数据
_this.allFeedback = data;
}
});
}
}
Angular2 - Starter - Routes, Route Resolver的更多相关文章
- [Angular2 Router] Resolving route data in Angular 2
From Article: RESOLVING ROUTE DATA IN ANGULAR 2 Github If you know Anuglar UI router, you must know ...
- [Angular2 Router] CanActivate Route Guard - An Example of An Asynchronous Route Guard
In this tutorial we are going to learn how we can to configure an can activate route guard in the An ...
- [Angular2 Router] CanDeactivate Route Guard - How To Confirm If The User Wants To Exit A Route
In this tutorial we are going to learn how we can to configure an exit guard in the Angular 2 Router ...
- [Angular2 Router] Optional Route Query Parameters - The queryParams Directive and the Query Parameters Observable
In this tutorial we are going to learn how to use the Angular 2 router to pass optional query parame ...
- Angular2 - Starter - Pipes, Custom Pipes
在Angular2 模板中,我们在显示数据时,可以使用通道将数据转换成相应的格式的值的形式来显示,而且这不改变源数据.比如,我们可以使用date通道来转换时间显示的格式: {{date | date: ...
- Angular2 - Starter - Component and Component Lifecircle Hooks
我们通过一个NgModule来启动一个ng app,NgModule通过bootstrap配置来指定应用的入口组件. @NgModule({ bootstrap: [ AppComponent ], ...
- [译]Angular2 和TypeScript -- 一次简要的预览
原文链接:https://www.infoq.com/articles/Angular2-TypeScript-High-Level-Overview 作者: Yakov Fain Posted o ...
- .net转php laraval框架学习系列(三)项目实战---Route&Controllers
本章来学习laravel的路由 一个简单的路由列子 Route::get('/', function() { return 'Hello World'; }); 路由的写法和Node的风格很相似.上面 ...
- Angular2 和TypeScript
Angular2 和TypeScript 原文链接:https://www.infoq.com/articles/Angular2-TypeScript-High-Level-Overview 作者: ...
随机推荐
- VS2012+EF6+Mysq
为了学习ORM,选择了EntityFramework,经历了三天两夜的煎熬,N多次错误,在群里高手的帮助下,终于成功,现在将我的心路历程记录下来,一是让自己有个记录,另外就是让其它人少走些弯路. 我的 ...
- Rsync数据远程同步备份
rsync的使用方法 一.设置Rsync Server端 Rsync server需要设定四个方面: 1.规划建立备份目录区 2.设定: /etc/xinetd.d/rsync 3.设定: /etc/ ...
- postfix日志分析pflogsumm
1.pflogsumm功能:统计接收.投递.转发.延时.反弹.拒绝.保留.丢弃的邮件统计发件人和收件人 统计发送和接受方主机/域名 统计SMTPD连接数...... 2.安装# yum install ...
- androidstudio 问题
Error:(1, 1) A problem occurred evaluating project ':app'. > Failed to apply plugin [id 'com.andr ...
- 2.1 sikuli 中编程运行
1.用sikuli编程时,多用wait()语句,因为很多时候没有给它一定的识别时间,就容易出错. 比如下图,保证页面加载时间 1.Sikuli中 ,可以加# 进行注释 但是注释有的时候也会不起作用,比 ...
- stdafx文件介绍
MSDN介绍: These files are used to build a precompiled header file Projname.pch and a precompiled types ...
- js框架——angular.js
这是一个前端用的框架,使用简单.详细介绍这里就不写了,主要介绍其语法和作用—— 1. 声明一个angular 如果想要使用一个angular代码,则需要在[想要使用angular的范围内写上ng-ap ...
- Git学习 -- 工作区和暂存区
工作区(working directory): 就是能看到的目录,如我的git文件夹 版本库(repository): 工作区有一个隐藏目录.git,这个不算工作区,而是Git的版本库 里面最重要的就 ...
- 关于VC中的错误处理
include <exception> try {} cache(exception &e) { cout<<e.what()<<endl; } 但 ...
- 使用MyBatis的Generator自动创建实体类和dao的接口与xml
在实际的项目中其实建立数据库和设计数据库的时候特别重要,而等数据库设计完成之后,根据数据库创建实体类的工作就特别麻烦和繁琐了,不仅很麻烦,而且很浪费时间,不做又不行,这次就找到了一个简单的方法可以让m ...