zoukankan      html  css  js  c++  java
  • ng2——路由小示例

    有用angular开发的一般都是单页面应用程序,单页面应用程序就离不开路由,下边是我自己写的一个简单的路由,我也是一个初学者,有什么不对的地方,请求指正。

    1.配置路由文件

    首先从angular模块中引入RouterModule和Routes,然后将组件引入,然后定义路由路径以及组件类

    代码

    import {RouterModule,Routes} from '@angular/router';
    
    import {Search} from './compontents/search/index';
    
    const routes:Routes = [
      {
        path:'',
        redirectTo:'/search',
        pathMatch:'full'
      },
      {
        path:'search',
        component:Search
        
      }
    ];
    
    export const routing = RouterModule.forRoot(routes);
    

    2.跟模块引入路由

    首先引入定义好的路由,然后在根模块的imports引入路由。

    代码

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';// 每个浏览器中中运行的应用都需要引入该插件 BrowserModule模块
    import { HashLocationStrategy, LocationStrategy } from '@angular/common';
    import { routing } from './app.router';
    
    import { Search } from './compontents/search/index';
    import { AppComponent } from './app.component';
    import { ClickMeComponent, KeyEvent} from './click-me.component';
    
    @NgModule({
      imports: [BrowserModule,routing],   // 当模块需要引入特性的时候通过imports引入到imports数组中 如http/router
      declarations: [AppComponent, ClickMeComponent, Search, KeyEvent],    // 每个组件必须在且仅在一个NgModule类中声明,管道和指令也必须在declarations中声明
      bootstrap: [AppComponent],     // 通过引导根AppModule来启动应用,
      providers: [
        {provide: LocationStrategy, useClass: HashLocationStrategy}
      ],
    })
    
    export class AppModule { }

    跟模块中的provider部分可以不设置,该处主要是设置url的格式,

    路由有两个显示格式:

    PathLocationStrategy - 默认的策略,支持“HTML 5 pushState”风格。显示方式为: http://localhost:3000/search
    HashLocationStrategy - 支持“hash URL”风格。显示方式为:http://localhost:3000/#/search

    3.在index.html文件中的header内部添加<base href='/'>

    4.在跟组件的template上添加

    <router-outlet></router-outlet>
    

    该处代码的作用是现实下级路由的父容器,类似ng-ui-router内部的ui-view,以及ionic路由部分的<ion-nav-view>

  • 相关阅读:
    微服务-分解应用程序从而实现更好的部署特性及可伸缩性
    <HTML5和CSS3响应式WEB设计指南>译者序
    使用亚马逊的Route53服务
    Java中测试异常的多种方式
    跑在路上的程序员随想
    使用ruby过程中遇到安装gem失败的一些通用解决方案
    Spring-Context之九:在bean定义中使用继承
    Spring-Context之八:一些依赖注入的小技巧
    配置ngnix
    PHP程序员进阶学习书籍参考指南
  • 原文地址:https://www.cnblogs.com/happen-/p/6388737.html
Copyright © 2011-2022 走看看