首页 > 语言 > JavaScript > 正文

Angular 4.x 路由快速入门学习

2024-05-06 15:17:41
字体:
来源:转载
供稿:网友

路由是 Angular 应用程序的核心,它加载与所请求路由相关联的组件,以及获取特定路由的相关数据。这允许我们通过控制不同的路由,获取不同的数据,从而渲染不同的页面。

接下来我们将按照以下目录的内容,介绍 Angular 的路由。具体目录如下:

目录

    Installing the router
      Base href
    Using the router
      RouterModule.forRoot RouterModule.forChild
    Configuring a route Displaying routes Futher configuration
      Dynamic routes Child routes Component-less routes loadChildren
    Router directives
      routerLink routerLinkActive
    Router API

Installing the router

首先第一件事,我们需要安装 Angular Router。你可以通过运行以下任一操作来执行此操作:

yarn add @angular/router# ORnpm i --save @angular/router

以上命令执行后,将会自动下载 @angular/router 模块到 node_modules 文件夹中。

Base href

我们需要做的最后一件事,是将 <base> 标签添加到我们的 index.html 文件中。路由需要根据这个来确定应用程序的根目录。例如,当我们转到 http://example.com/page1 时,如果我们没有定义应用程序的基础路径,路由将无法知道我们的应用的托管地址是 http://example.com 还是 http://example.com/page1

这件事操作起来很简单,只需打开项目中的 index.html 文件,添加相应的 <base> 标签,具体如下:

<!doctype html><html> <head> <base href="/" rel="external nofollow" > <title>Application</title> </head> <body> <app-root></app-root> </body></html>

以上配置信息告诉 Angular 路由,应用程序的根目录是 /

Using the router

要使用路由,我们需要在 AppModule 模块中,导入 RouterModule 。具体如下:

import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { RouterModule } from '@angular/router';import { AppComponent } from './app.component';@NgModule({ imports: [ BrowserModule, RouterModule ], bootstrap: [ AppComponent ], declarations: [ AppComponent ]})export class AppModule {}

此时我们的路由还不能正常工作,因为我们还未配置应用程序路由的相关信息。RouterModule 对象为我们提供了两个静态的方法:forRoot() forChild() 来配置路由信息。

RouterModule.forRoot()

RouterModule.forRoot() 方法用于在主模块中定义主要的路由信息,通过调用该方法使得我们的主模块可以访问路由模块中定义的所有指令。接下来我们来看一下如何使用

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选