GVKun编程网logo

简单讲解AngularJS的Routing路由的定义与使用(angularjs router)

23

在这篇文章中,我们将为您详细介绍简单讲解AngularJS的Routing路由的定义与使用的内容,并且讨论关于angularjsrouter的相关问题。此外,我们还会涉及一些关于angularrout

在这篇文章中,我们将为您详细介绍简单讲解AngularJS的Routing路由的定义与使用的内容,并且讨论关于angularjs router的相关问题。此外,我们还会涉及一些关于angular router 路由的简单实用、Angular routing生成路由和路由的跳转、angular – 对子路由的RouterLinkActive都是false、angularjs $route(路由) 的使用的知识,以帮助您更全面地了解这个主题。

本文目录一览:

简单讲解AngularJS的Routing路由的定义与使用(angularjs router)

简单讲解AngularJS的Routing路由的定义与使用(angularjs router)

在单页面应用中,视图之间的跳转就显尤为重要的,随着应用越来越复杂,我们需要用一种方法来精确控制什么时候该呈现怎样的页面给用户。

咱们可以通过在主页面中引入不同的模板来支持不同页面的切换,但是这么做的缺点就是,越来越多的内嵌代码导致最后难以管理。

通过ng-include指令我们可以把很多的模板整合在视图中,但是我们有更好的方法来处理这种情况,我们可以把视图打散成layout和模板视图,然后根据用户访问的特定的URL来显示需要的视图

我们可以将这些“碎片”在一个布局模板中拼接起来

AngularJS通过在$routeProvider($route服务的提供者)上声明routes来实现上面的构想

使用$routeProvider,我们可以更好的利用浏览历史的API并且可以让用户可以把当前路径存成书签以方便以后的使用

在我们的应用中设定路由,我们需要做两件事情:第一,我们需要指出我们存放将要存放新页面内容的布局模板在哪里。比如,如果我们想在所有页面都配上header和footer,我们可以这样设计布局模板:

rush:js;">

Header

Footer

angular router 路由的简单实用

angular router 路由的简单实用

angular路由的使用

  1. 首先要添加了路由服务文件(在创建项目的时候会询问,如果当时没有创建俺的话需要手动创建)

  2. 下边是一个现成的路由文件,可以参考

//app.module.ts
 import { NgModule } from ''@angular/core'';
 import { Routes, RouterModule } from ''@angular/router'';
 ​
 import { SignupComponent } from "./components/signup/signup.component";
 import { SigninComponent } from "./components/signin/signin.component";
 import { LayoutComponent } from "./components/layout/layout.component";
 import { ContactListComponent } from "./components/contact-list/contact-list.component";
 import { ContactEditComponent } from "./components/contact-edit/contact-edit.component";
 import { ContactNewComponent } from "./components/contact-new/contact-new.component";
 ​
 import { TagListComponent } from "./components/tag-list/tag-list.component";
 import { TagEditComponent } from "./components/tag-edit/tag-edit.component";
 import { TagNewComponent } from "./components/tag-new/tag-new.component";
 ​
 import {AuthGuard} from ''./auth_guard.service''
 ​
 const routes: Routes = [ //路由对象
   {
     path:'''',
     redirectTo:''/contacts'',//当请求根路径的时候,跳转到contacts路径
     pathMatch:''full'' //必须完全匹配到路径的时候才做路由重定向
   },
   {
     path:''layout'',
     component: LayoutComponent
   },
   {
     path:''contacts'',
     component: LayoutComponent,
     canActivate: [AuthGuard], // 在导航 contacts 之前会先进入路由守卫
     children:[ //子路由设置
       {
         path:'''',
         component: ContactListComponent,
       },
       {
         path:''edit/:id'',// 路由传参
         component: ContactEditComponent
       },
       {
         path:''new'',
         component: ContactNewComponent
       },
 ​
     ]
   },
   {
     path:''tags'',
     component: LayoutComponent,
     canActivate: [AuthGuard], // 在导航 contacts 之前会先进入路由守卫
 ​
     children:[
       {
         path:'''',
         component: TagListComponent,
       },
       {
         path:''edit'',
         component: TagEditComponent
       },
       {
         path:''new'',
         component: TagNewComponent
       },
 ​
     ]
   },
   {
     path:''signin'',
     component: SigninComponent
   },
   {
     path:''signup'',
     component: SignupComponent
   },
 ​
 ];
 ​
 @NgModule({
   imports: [RouterModule.forRoot(routes)],
   exports: [RouterModule],
   providers: [AuthGuard]
 })
 export class AppRoutingModule { }
 ​

路由守卫服务文件也贴上,方便对照

 
//auth_guard.service.ts
import { Injectable }     from ''@angular/core'';
 import { CanActivate, Router }    from ''@angular/router'';
 ​
 @Injectable()
 export class AuthGuard implements CanActivate {
   constructor (
     private router: Router
   ) {}
   canActivate() {
     const token = window.localStorage.getItem(''auth_token'') 
     //这个 token 是我的angular APP验证用的东西,验证通过则跳转可以访问路由,不通过则跳转登录页
     if (!token) {
       this.router.navigate([''/signin''])
       return false // 不能继续导航
     }
     // 如果验证通过,则放行,继续完成导航
     return true;
   }
 }
 ​

如果配置过程中出现问题的话,建议查看app.module中是否注入路由文件依赖。

总结

以上是小编为你收集整理的angular router 路由的简单实用全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

原文地址:https://blog.csdn.net/xawjz/article/details/118761102

Angular routing生成路由和路由的跳转

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>

   

分享图片

    

分享图片

我们最简单的路由写完了!!!

但是我们发现一个问题,当我们初始化整个项目的时候,默认是没有组件的

  

@H_168_301@

我们如果想一进来就加载首页组件,就涉及到默认的跳转路由!

默认加载组件(空路由)

  {
    path:‘‘,// 空路由
    redirectTo:‘home‘,// 重定向到
    pathMatch:‘full‘
  }

  

分享图片

如果路由输入错误,还是跳回首页(也可以匹配空路由)

 // 匹配不到路由时候加载的组件
  {
    path:‘**‘,// 任意路由
    component:HomeComponent
  }

  

分享图片

在已经创建好的没有路由项目中,使用路由

angular – 对子路由的RouterLinkActive都是false

angular – 对子路由的RouterLinkActive都是false

我有以下儿童路线:

{ path: '',component: LoginSingupComponent,children: [
    { path: 'login',component: LoginComponent },{ path: 'singup',component: SingupComponent },]
},

导航到/ login或/ singup工作正常(加载了正确的组件).

这是LoginSingupComponent的摘录

<nav md-tab-nav-bar>
  <a md-tab-link routerLink="/login" routerLinkActive [routerLinkActiveOptions]="{exact: true}" #rla="routerLinkActive" [active]="rla.isActive">Entrar {{rla.isActive}}</a>
  <a md-tab-link routerLink="/singup" routerLinkActive [routerLinkActiveOptions]="{exact: true}" #rla="routerLinkActive" [active]="rla.isActive">Criar uma conta{{rla.isActive}}</a>
</nav>

当打开/登录时,所有rla.isActive == false,当打开/ singup时,所有rla.isActive == true

尝试使用和不使用exact:true

解决方法

试试这样:

<nav md-tab-nav-bar>
    <a md-tab-link [routerLink]="['/']" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Home</a>
    <a md-tab-link [routerLink]="['/login']" routerLinkActive="active">Login</a>
    <a md-tab-link [routerLink]="['/singup']" routerLinkActive="active">Signup</a>
</nav>

angularjs $route(路由) 的使用

angularjs $route(路由) 的使用

######$route被用于URLS到controller和view(HTML模板)之间的链接,它会监控$location.url()并试图对此路径及对应的路由配置进行映射,使用时需要安装ngroute模块:

在模板主页header上添加:

<pre><code> &lt;script src="../js/angular-route.min.js">&lt;/script></code></pre>

index.html:

<pre></code> &lt;!doctype html> &lt;html xmlns:ng="http://angularjs.org" ng-app=''app'' ng-csp="" scroll id="ng-app"> &lt;head> &lt;meta charset="UTF-8"> &lt;title>angularjs route&lt;/title> &lt;link rel="stylesheet" href="../css/bootstrap.css"/> &lt;script src="../js/angular.min.js">&lt;/script> &lt;script src="../js/angular-animate.min.js">&lt;/script> &lt;script src="../js/angular-route.min.js">&lt;/script> &lt;script src="../js/main.js">&lt;/script> &lt;/head> &lt;body> &lt;div> &lt;a href="#/">主页&lt;/a>&lt;a href="#/other">其他页&lt;/a> &lt;/div> &lt;div ng-view>&lt;/div> &lt;/body> &lt;/html> </code></pre>

other.html:

<pre><cdoe>&lt;h1>{{title}}&lt;/h1></code></pre>

home.html:

<pre><cdoe>&lt;h1>{{title}}&lt;/h1></code></pre>

使用方式为,在main.js中添加:

<pre><code> var app = angular.module(''app'', [ ''ngRoute'' ]) .config(function ($routeProvider){ $routeProvider .when(''/other'', { controller: ''otherCtrl'', templateUrl: ''content/views/other.html'', publicAccess: true }) .when(''/'', { controller: ''homeCtrl'', templateUrl: ''content/views/home.html'' }) .when(''/other/:id'', { controller: ''otherDetailCtrl'', templateUrl: ''content/views/otherDetail.html'', publicAccess: true }) .otherwise({ redirectTo: ''/'' }); } app.controller(''homeCtrl'',function($scope,$http){ console.log(''i am home page''); $scope.title = ''i am home page''; }).controller(''otherCtrl'',function($scope){ console.log(''i am other page''); $scope.title = ''i am other page''; }).controller(''otherDetailCtrl'',function($scope, $routeParams, $location){ var id = $routeParams.id; if(id == 0) { $location.path(''/other''); } console.log(''i am otherDetailCtrl page''); $scope.title = ''i am otherDetailCtrl page''; }); </code></pre>

当打开index.html时,会自动打开''/'',当点击导航中“主页”、“其他页”时,会进行页面切换。

在$route(路由)中,提供了两个依赖性服务:$location、$routeParams; $location、$routeParams均可在controller中使用,如上otherDetailCtrl中,可通过$routeParams获取路由时所传参数,可通过$location进行路由跳转。

我们今天的关于简单讲解AngularJS的Routing路由的定义与使用angularjs router的分享就到这里,谢谢您的阅读,如果想了解更多关于angular router 路由的简单实用、Angular routing生成路由和路由的跳转、angular – 对子路由的RouterLinkActive都是false、angularjs $route(路由) 的使用的相关信息,可以在本站进行搜索。

本文标签:

上一篇在AngularJS框架中处理数据建模的方式解析(angularjs module)

下一篇整理AngularJS框架使用过程当中的一些性能优化要点(angularjs框架怎么搭)