angular入门基础教程(七)系统路由

发布于:2024-08-01 ⋅ 阅读:(129) ⋅ 点赞:(0)

路由的实现

当我们系统越来复杂,功能越来越多,路由也就是必须的了。在 ng 中如何实现路由呢?

启用路由

  • 在 app 目录下,新建一个 router 目录,把 app.routers.ts 文件拷贝过来,并修改一下。
import { Routes } from "@angular/router";
export const routes: Routes = [];
  • 在 app.config.ts 中,引入 router 模块
import { ApplicationConfig } from "@angular/core";
import { provideRouter } from "@angular/router";
import { routes } from "./app.routes";
export const appConfig: ApplicationConfig = {
  //注入路由
  providers: [provideRouter(routes)],
};
  • 在 main.ts 中,初始化 app 的配置
import { bootstrapApplication } from "@angular/platform-browser";
import { appConfig } from "./app/app.config";
import { AppComponent } from "./app/app.component";

bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));

定义路由

  • 在 app.routes.ts 中,定义路由

    • path 前面不能有’/‘,否则会报错’,ng 渲染后 会自动给我们加上’/',不用我们手动加
    • a 的 routerLink 属性,必须和 path 对应,否则会报错
    • a的href属性不能用了,切换时页面会刷新闪烁,routerLink不会
    • 路由的 component,引入路径不对,会提示组件类型找不到的暴红
    • 路由的 title,在浏览器中,标题栏会显示这个,是自动给我们显示,不用我们手动赋值
import { Routes } from "@angular/router";
import { HomeComponent } from "./home/home.component";
import { AboutComponent } from "./about/about.component";
export const routes: Routes = [
  {
    path: "/",
    component: HomeComponent,
    title: "首页",
  },
  {
    path: "/about",
    component: AboutComponent,
    title: "关于",
  },
];

请添加图片描述

错误排查

  • 这种是引入的路径不对,导致爆红
    在这里插入图片描述

网站公告

今日签到

点亮在社区的每一天
去签到