如果您想了解【Angular】路由跳转(代码跳转)和angular路由跳转的知识,那么本篇文章将是您的不二之选。我们将深入剖析【Angular】路由跳转(代码跳转)的各个方面,并为您解答angular
如果您想了解【Angular】路由跳转(代码跳转)和angular 路由跳转的知识,那么本篇文章将是您的不二之选。我们将深入剖析【Angular】路由跳转(代码跳转)的各个方面,并为您解答angular 路由跳转的疑在这篇文章中,我们将为您介绍【Angular】路由跳转(代码跳转)的相关知识,同时也会详细的解释angular 路由跳转的运用方法,并给出实际的案例分析,希望能帮助到您!
本文目录一览:- 【Angular】路由跳转(代码跳转)(angular 路由跳转)
- Angular routing生成路由和路由的跳转
- Angular 利用路由跳转到指定页面的指定位置方法
- angular 未登录状态拦截路由跳转的方法
- angular 路由策略相关问题 (包含路由跳转以后原页面没有进destory方法的原因和处理)
【Angular】路由跳转(代码跳转)(angular 路由跳转)
【WHAT】
在Angular中,路由的作用就是建立URL路径和组件(页面,因为页面就是由组件构成)之间的对应关系,根据不同的URL路径匹配出相应的组件并渲染。
【HOW】
1. 定义路由配置
2. 创建根路由模块
3. 添加路由插座
(以上是基本且必须的三个步骤)
【示例:(文件如下)】
1.在app.routes定义路由,主要设置有:
- 设置启动的第一个路由
- 定义要在根目录下启动所有子路由
export const AppRoutes=[ { path: '',redirectTo: 'showmain',//项目启动的第一个路由为showmain pathMatch: 'full' },{ path: 'showmain',loadChildren: './showmain/showmain.module#ShowmainModule' },{ path: 'login',loadChildren: './login/login.module#LoginModule' } ]
2.创建根路由(app.module.ts),主要设置有
- 设置根路由
import { browserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import {RouterModule} from '@angular/router'; //导入路由 import { AppComponent } from './app.component'; import {AppRoutes} from './app.routes'; @NgModule({ declarations: [ AppComponent ],imports: [ browserModule,FormsModule,HttpModule,RouterModule,//设置主要路由 RouterModule.forRoot(AppRoutes) ],providers: [],bootstrap: [AppComponent] }) export class AppModule { }
3.定义插座(在app.component.html)
<router-outlet></router-outlet>
4.定义子路由showmain.routes.ts
import { ShowmainComponent } from './showmain.component'; export const ShowmainRoutes= [ { path: '',component: ShowmainComponent } ]
5.设置子路由ShowmainRoutes
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import {RouterModule} from '@angular/router'; import {ShowmainRoutes} from './showmain.routes'; import { ShowmainComponent } from './showmain.component'; @NgModule({ imports: [ CommonModule,//设置ShowmainRoutes为子路由 RouterModule.forChild(<any>ShowmainRoutes) ],declarations: [ ShowmainComponent ] }) export class ShowmainModule { }
6.设置跳转的下一个子路由login
在showmain.component.ts文件中设置在doIn()触发时跳转路由
import { Component,OnInit } from '@angular/core'; import { Router} from '@angular/router'; //导入router服务 @Component({ selector: 'app-showmain',templateUrl: './showmain.component.html',styleUrls: ['./showmain.component.css'] }) export class ShowmainComponent implements OnInit { constructor(private router: Router) { } ngOnInit() { } doIn(): void { //跳转到login路由(绝对路径) this.router.navigateByUrl("login") } }
(之所以第二个页面要设置跳转,而跳转到第一个子路由没用到该句,是因为在根路由下已设置了项目启动后跳转的第一个路由)
- 在showmain.component.html设置页面
<h1>欢迎加入大米时代!</h1> <button (click)="doIn()">进入系统</button>
7.定义第二个子路由LoginRoutes
login.routes.ts
import { LoginComponent } from './login.component'; export const LoginRoutes= [ { path: '',component: LoginComponent } ]
8.设置LoginRoutes为子路由
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import {RouterModule} from '@angular/router'; import{FormsModule}from '@angular/forms'; import { LoginRoutes } from './login.routes'; import { LoginComponent } from './login.component'; @NgModule({ imports: [ CommonModule,//必须导入FormsMoudule,因为此页面用到了数据双向绑定 FormsModule,//将LoginRoutes设置为子路由 RouterModule.forChild(<any>LoginRoutes) ],declarations: [ LoginComponent ] }) export class LoginModule { }
9.设置第二个路由即页面的主要内容
login.component.ts文件
import { Component,OnInit } from '@angular/core'; @Component({ selector: 'app-login',templateUrl: './login.component.html',styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { public username:string; public password:string; doLogin() { //必须写this let username = this.username; let password = this.password; if (username == "1" && password == "1"){ alert("登录成功") } else{ alert("登录失败") } } }
login.component.html文件
<div class="login"> <h1>前台登录</h1> </div> <div> <label for="">用户名:</label> <input name ="username" type="text" [(ngModel)]="username"> </div> <div> <label for="">密 码:</label> <input name ="password" type="text" [(ngModel)]="password"> </div> <button (click)="doLogin()">登录</button>
程序执行,访问文件的顺序依次是:
思路是这样的:
在app.module中设置了根路由AppRoutes,于是开始执行app.module中,而app.module设置了跳转的第一个子路由showmain,在此文件中有该路由,于是去设置的路径下去找ShowmainModule,于是执行到了showmain.module,去showmain.routes找该路由,该路由被渲染的组件为ShowmainComponent,于是又执行到了showmain.component文件中,而此文件中又设置了一个绝对路径下的路由login,于是又执行到app.routes下查找有无该路由,有则跳转到指定目录下的login.module文件下找LoginModule,在login.module定义了该路由LoginRoutes,于是去login.routes找到了该路由,该路由被渲染的组件为LoginComponent,于是去login.component文件中找到该组件,执行方法,结束![之所以回去app.routes下查找路由,是根据它设置的找路径找的this.router.navigateByUrl("login")
]
【扩展】
- declarations:声明自己写的东西(如组件)
- imports:通常是导入程序已封装号的东西(如router的forRoot()方法)
快捷键
- 新建文件(指定目录下):
ng g c 文件名
- 新建module:
ng g module 名称
- 启动服务的同时在浏览器中打开:
ng serve --open
- 该运行的端口:
ng serve --port 端口号
- 标签:
直接打标签名+双击Tab(不用输<)
- 新建文件(指定目录下):
有数值双向绑定时,无论html中用没用到表单,都要导入forms:
import { FormsModule } from '@angular/forms';
Angular routing生成路由和路由的跳转
Angular routing生成路由和路由的跳转
什么是路由
路由的目的是可以让根组件按照不同的需求动态加载不同的组件。
根据不同地址,加载不同组件,实现单页面应用。
Angular 命令创建一个配置好路由的项目
命令创建项目
ng new demo02 --routing
安装依赖
npm install
启动项目
ng serve --open
与没有创建路由的项目比较
创建路由项目的文件比没有创建路由项目的文件多了一个 app-routing.module.ts 文件。
然后在 app.module.ts 文件中引入了路由文件。
在 app.component.html 文件中加入了动态加载组件显示的地方。
路由学习案例
创建组件
创建几个组件,首先创建一个 components 文件夹存放将要创建的组件。
创建home组件
ng g component components/home
创建news组件
ng g component components/news
创建user组件
ng g component components/user
配置路由,点击不同的导航显示不同组件
在 app-routing.module.ts 中配置路由。
首先引入组件
// 引入组件 import {HomeComponent} from ''./components/home/home.component'' import {NewsComponent} from ''./components/news/news.component'' import {UserComponent} from ''./components/user/user.component''
配置路由
// 配置路由 const routes: Routes = [ { path:''home'', component:HomeComponent, }, { path:''news'', component:NewsComponent, }, { path:''user'', component:UserComponent, } ];
添加导航按钮
在根组件 app.component.html 文件中添加导航。
<header> <ul> <li><a routerLink="home" >首页</a></li> <li><a routerLink="news" >新闻</a></li> <li><a routerLink="user" >用户</a></li> </ul> </header>
我们最简单的路由写完了!!!
但是我们发现一个问题,当我们初始化整个项目的时候,默认是没有组件的
我们如果想一进来就加载首页组件,就涉及到默认的跳转路由!
默认加载组件(空路由)
{ path:'''', // 空路由 redirectTo:''home'', // 重定向到 pathMatch:''full'' }
如果路由输入错误,还是跳回首页(也可以匹配空路由)
// 匹配不到路由时候加载的组件 { path:''**'', // 任意路由 component:HomeComponent }
在已经创建好的没有路由项目中,使用路由
总结
以上是小编为你收集整理的Angular routing生成路由和路由的跳转全部内容。
如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。
原文地址:https://www.cnblogs.com/wjw1014/p/10354482.html
Angular 利用路由跳转到指定页面的指定位置方法
之前做过页面内的跳转,比较简单,最近项目需要实现跨页面跳转,并跳转到指定地点,试了很多方法,有用到传递参数然后让页面滚动相应的距离,但是一旦文章长短发生变化,滚动的距离也需要重新计算,比较麻烦,所以最后总结出这两种比较靠谱的方法,只需要在需要跳转的地方加上合适的id就行,原理和单页面内跳转相似。
detail.component.html
<p>You''ll see which payment methods are available to you on the checkout page, before you submit a reservation request. After you select your country, all of your payment details will be shown.</p> <p id="readMore">We charge featured guide who offer journey a 15% service fee. The amount of the service fee is calculated from the price that featured guide set for their journey. You will see the service fee when you set your price before submitting a journey. The service fee is automatically deducted from the payout to the Host. Depending on the laws of the jurisdiction involved, VAT may be charged on top of the service fee. The service fee will include these VAT charges when applicable.</p>
app.component.html
<button (click)="readMore()">ReadMore</button>
app.route.ts
{ path: '''',component: LoginComponent}, { path: ''detail'', component: DetailComponent }, { path: ''**'',component: NotFoundComponent}
方法一:新增路由地址来实现
app.route.ts
{ path: '''',component: LoginComponent}, { path: ''detail'', component: DetailComponent }, { path: ''detail#readMore'',component: NotFoundComponent}, { path: ''**'',component: NotFoundComponent}
app.component.ts
readMore() { this.router.navigateByUrl(''/detail#readMore''); }
detail.component.ts
ngOnInit() { if (window.location.hash === ''#readMore'') { window.location.assign(''detail#readMore''); } }
方法二:在原路由地址不变的情况下,利用路由传递参数来实现
app.component.ts
readMore() { this.router.navigate([''/detail'', { id: ''readMore''}]); } detail.component.ts this.myActivatedRoute.params.subscribe( (data: any) => { if (data.id === ''readMore'') { window.location.assign(''detail#readMore''); } } );
以上这篇Angular 利用路由跳转到指定页面的指定位置方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
- AngularJS路由实现页面跳转实例
- AngularJS实现单一页面内设置跳转路由的方法
- angularjs项目的页面跳转如何实现(5种方法)
- angular2中router路由跳转navigate的使用与刷新页面问题详解
angular 未登录状态拦截路由跳转的方法
使用angularjs的但页面应用时,由于是本地路由在控制页面跳转,但是有的时候我们需要判断用户是否登录来判断用户是否能进入界面。
angularjs是mvc架构所以实现起来很容易也很灵活,我们只MainController里增加一个路由事件侦听并判断,这样就可以避免未登录用户直接输入路由地址来跳转到登录界面地址了。
第一步:定义myapp
var myapp=angular.module("MainController",["ui.router",''infinite-scroll'',''oc.lazyLoad'']);
第二步:使用config来配置路由跳转
myapp.config( function($stateProvider,$urlRouterProvider,$ocLazyLoadProvider,$httpProvider){ $stateProvider .state(''index'', {//首页 url: ''/index'', templateUrl: basePath+''page/gym/lecycle_index.html'', resolve: { loadMyCtrl: [''$ocLazyLoad'', function($ocLazyLoad){//这两行就是loader的使用,此行写法固定 return $ocLazyLoad.load(basePath+''src/lecycle_index/le_index.js'');//后面这个就是进入这个模板时候要加载进来的js }] } }) .state(''userAgree'',{//同意用户协议页面 url:"/userAgree", templateUrl:basePath+''page/agreement.html'' }) ....... $urlRouterProvider.otherwise("/index");/*BproDtails*/ });
第三步:使用run来进行登录验证拦截
myapp.run(function ($rootScope,$state) { $rootScope.$on(''$stateChangeStart'',function(event){ // if(toState.name==''login'')return;// 如果是进入登录界面则允许 // 如果用户不存在 if(ifLoginTrue==false){ console.log("没有登录") event.preventDefault();// 取消默认跳转行为 $("#my-modal-loading").modal(''open'');//开启加载中loading // $state.go("login",{from:fromState.name,w:''notLogin''});//跳转到登录界面 } }); });
以上这篇angular 未登录状态拦截路由跳转的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
- AngularJS实现用户登录状态判断的方法(Model添加拦截过滤器,路由增加限制)
- Angular 利用路由跳转到指定页面的指定位置方法
- 详解Angular4中路由Router类的跳转navigate
- AngularJS路由实现页面跳转实例
- AngularJS实现单一页面内设置跳转路由的方法
- angular4 如何在全局设置路由跳转动画的方法
angular 路由策略相关问题 (包含路由跳转以后原页面没有进destory方法的原因和处理)
angular中,不同路由不同页面之间跳转的时候在不做任何处理的时候是会直接销毁原页面,如果页面没有销毁,那就一定是采用了路由复用。
如下图,在没有采用路由复用的策略的时候,可以看到在页面切换的时候是会直接销毁原页面的。
而采用了路由复用策略以后,可以看到跳转以后,原页面并没有销毁。
要怎么做其实很简单,angular 原生提供了路由相关的接口,首先新建一个ts文件
然后继承angular提供的路由策略接口
对接口进行修改,代码如下
import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from "@angular/router"; interface RouterStroageObject { snapshot: ActivatedRouteSnapshot; handle: DetachedRouteHandle; } export class RouterStrategy implements RouteReuseStrategy { storedRoutes: { [key: string]: RouterStroageObject } = {}; storedData: { [key: string]: any } = {}; /** * * 路由离开时是否需要保存页面,这是实现自定义路由复用策略最重要的一个方法。 其中: 返回值为true时,路由离开时保存页面信息,当路由再次激活时,会直接显示保存的页面。 返回值为false时,路由离开时直接销毁组件,当路由再次激活时,直接初始化为新页面。 */ shouldDetach(route: ActivatedRouteSnapshot): boolean { // console.log(''shouldDetach的事件中的route'', route) if (route.data.noReuse) { return false } return true } /** 如果shouldDetach方法返回true,会调用这个方法来保存页面。 */ store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void { // console.log(''store的事件'', ''route'', route, ''handle'', handle); const storedRoute: RouterStroageObject = { snapshot: route, handle: handle } this.storedRoutes[this.getRouteUrl(route)] = storedRoute; // console.log(''this.storedRoutes'', this.storedRoutes) } /** * 路由进入页面时是否有页面可以重用。 true: 重用页面,false:生成新的页面 */ shouldAttach(route: ActivatedRouteSnapshot): boolean { return !!route.routeConfig && !!this.storedRoutes[this.getRouteUrl(route)]; } /** * 路由激活时获取保存的页面,如果返回null,则生成新页面 */ retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null { if (!route.routeConfig || route.routeConfig.loadChildren || !this.storedRoutes[this.getRouteUrl(route)]) { return null } return this.storedRoutes[this.getRouteUrl(route)].handle } /** * 决定跳转后是否可以使用跳转前的路由页面,即跳转前后跳转后使用相同的页面 */ shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { return future.routeConfig === curr.routeConfig && JSON.stringify(future.params) === JSON.stringify(curr.params); } private getRouteUrl(route: ActivatedRouteSnapshot) { //@ts-ignore const url = route[''_routerState''].url; const path = url.replace(/\//g, ''_'') + ''_'' + (route.routeConfig?.loadChildren || route.routeConfig?.component?.toString().split(''('')[0].split('' '')[1]); return path } }
保存以后,在要使用的路由文件中引入
import { NgModule } from ''@angular/core''; import { RouteReuseStrategy, RouterModule, Routes } from ''@angular/router''; import { RouterStrategy } from ''./routerStrategy''; import { Test1ComponentComponent } from ''./test1-component/test1-component.component''; import { Test2ComponentComponent } from ''./test2-component/test2-component.component''; const routes: Routes = [ { path:'''',pathMatch:''full'',redirectTo:''/test1'' }, { path:''test1'',component:Test1ComponentComponent,data:{noReuse:false} }, { path:''test2'',component:Test2ComponentComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers:[ {provide:RouteReuseStrategy,useClass:RouterStrategy} ] }) export class AppRoutingModule { }
如果我把noReuse的值改为true那么Test1页面跳转以后就会被销毁,如果设为false或者不设,跳转以后就不会被销毁
今天关于【Angular】路由跳转(代码跳转)和angular 路由跳转的分享就到这里,希望大家有所收获,若想了解更多关于Angular routing生成路由和路由的跳转、Angular 利用路由跳转到指定页面的指定位置方法、angular 未登录状态拦截路由跳转的方法、angular 路由策略相关问题 (包含路由跳转以后原页面没有进destory方法的原因和处理)等相关知识,可以在本站进行查询。
本文标签: