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 作者: ...
随机推荐
- ftp以及smb的配置
linux下ftp服务的配置1,打开终端,cd /etc/vsftpd2 vi vsftpd.conf3 相关的都打开说明: anonymous_enable=YES //允许匿名 ...
- PHP错误异常处理详解【转载】
异常处理(又称为错误处理)功能提供了处理程序运行时出现的错误或异常情况的方法. 异常处理通常是防止未知错误产生所采取的处理措施.异常处理的好处是你不用再绞尽脑汁去考虑各种错误,这为处理某一类错误提供了 ...
- dfs Codeforces Round #356 (Div. 2) D
http://codeforces.com/contest/680/problem/D 题目大意:给你一个大小为X的空间(X<=m),在该空间内,我们要尽量的放一个体积为a*a*a的立方体,且每 ...
- flex日期合并与拆分
<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="ht ...
- php 执行效率
用单引号代替双引号来包含字符串,这样做会更快一些.因为PHP会在双引号包围的字符串中搜寻变量,单引号则 不会,注意:只有echo能这么做,它是一种可以把多个字符串当作参数的“函数”(译注:PHP手册中 ...
- ubuntu上的mysql数据库双机备份设置
配置环境: myslq 5.5.3 + ubuntu server 12.04 一.配置MySQL主服务器(192.168.0.1) 1.增加一个账号专门用于同步 1 mysql>grant r ...
- 每个黑客黑客的目标是让目标系统做你不想做的事情。 一个主要的例子是显示敏感文件,如/ etc / passwd和/ etc / shadow(存储用户的用户名和加密密码)。一旦这些文件在他或她的手中,就可以使用“字典“攻击的密码。 或者,他们可以使您的系统FTP受感染的文件,并运行它,这可能是坏或坏。为了做到这一点,他们需要得到一个“可信”的程序来执行他们指定的命令。通常,这是通过“缓冲区
因此,本质上,程序正在读取文本行,解释它们,并基于它们执行操作.这些"网络守护进程"利用的一个方便的特征是它们可以使用"标准输入"和"标准输出&quo ...
- MongoDB如何设置权限(类似关系型数据库的用户名和密码)
MongoDB 缺省是没有设置鉴权的,业界大部分使用 MongoDB 的项目也没有设置访问权限.这就意味着只要知道 MongoDB 服务器的端口,任何能访问到这台服务器的人都可以查询和操作 Mongo ...
- win10系统安装oracle11g时遇到INS-13001环境不满足最低要求
升级win10系统之后,需要重新安装Oracle,因为在安装Oralce11g时,使用64位的会出现各种不兼容问题,我每次安装都是使用32位的数据库. 在安装时点击setup.exe之后,出现了:[I ...
- discuz 添加板块失败解决办法
最近把服务器环境升了下级,发现discuz后台添加栏目添加不了了,数据库没变,源代码没变,就突然添加不了了.刚开始添加1个板块成功了,再添加就怎么也添不进去了.只是页面刷新了一下,啥提示没有. 经过一 ...