Angular19学习笔记(day2)

前言

上一篇Angular学习笔记写完没多久,被毕业的事情耽搁了(各种材料、准备答辩等),现在终于忙完了,可以继续学了。先去回顾了一下day1的一系列概念,然后再去熟悉了一下day1写的项目。废话不多说,开始记录Angular第二篇笔记。

一、路由

路由是指从应用中的一个组件导航到另一个组件的能力。在单页应用(SPA)中,只会更新页面的部分内容,以呈现用户所请求的视图。那么我们该如何创建和配置路由呢?
首先在main.ts里面更新代码以启用路由

/*
 *  Protractor support is deprecated in Angular.
 *  Protractor is used in this example for compatibility with Angular documentation tools.
 */
import {
  bootstrapApplication,
  provideProtractorTestingSupport,
} from "@angular/platform-browser";
import { AppComponent } from "./app/app.component";
import { provideRouter } from "@angular/router";
import routeConfig from "./app/routes";

bootstrapApplication(AppComponent, {
  providers: [provideProtractorTestingSupport(),provideRouter(routeConfig)],
}).catch((err) => console.error(err));

main.ts中,我们引入了routeConfig和provideRouter,路由配置通过 provideRouter(routeConfig) 注入,配合 routes.ts 文件实现页面导航。

新建一个routes.ts文件夹,写入:

// routers.ts
import {Routes} from '@angular/router'; // 导入路由所需依赖
import {HomeComponent} from './home/home.component'; // 路由组件1
import {DetailsComponent} from './details/details.component';// 路由组件2

const routeConfig: Routes = [
  {
    path: '', // 匹配路径,这里为空代表默认
    component: HomeComponent, // 要渲染的路由组件
    title: 'Home page', // 路由跳转过去后,浏览器页签上面会显示的名字
  },
  {
    path: 'details/:id', // 动态路由,:id标记参数占位符,后续可以在路径中添加参数来传递动态值
    component: DetailsComponent,
    title: 'Home details',
  },
];
export default routeConfig;

除了上面给出的以外,还有很多其他的参数,比如:

  • path :路由路径。
  • component :要渲染的组件。
  • redirectTo :重定向到其他路径。
  • pathMatch :匹配方式(如 ‘full’、‘prefix’)。
  • children :子路由(嵌套路由)。
  • canActivate 、 canDeactivate :路由守卫。
  • data :自定义数据对象,可在路由守卫或组件中读取。
  • loadChildren :懒加载模块。
  • resolve :路由数据预加载。
  • title :页面标题。

创建路由之后,下一步添加路由

// app.component.ts
import {Component} from '@angular/core';
import {HomeComponent} from './home/home.component';
import {RouterModule} from '@angular/router';
@Component({
  selector: 'app-root',
  imports: [HomeComponent, RouterModule],
  template: `
    <main>
      <a [routerLink]="['/']">
        <header class="brand-name">
          <img class="brand-logo" src="/assets/logo.svg" alt="logo" aria-hidden="true" />
        </header>
      </a>
      <section class="content">
        <router-outlet></router-outlet>
      </section>
    </main>
  `,
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  title = 'homes';
}

这里使用了<a>标签来包裹目标元素,并通过设置routerLink属性来指定点击标签后跳转的路径。那如果我们想用动态路由,跳转的时候传递一个参数呢?
我们可以这样子实现:

页面上添加a标签,配合上routerlink,点击的时候传递参数

<section class="listing">
  <img
    class="listing-photo"
    [src]="housingLocation.photo"
    alt="Exterior photo of {{ housingLocation.name }}"
    crossorigin
  />
  <h2 class="listing-heading">{{ housingLocation.name }}</h2>
  <p class="listing-location">{{ housingLocation.city }}, {{ housingLocation.state }}</p>
  <a [routerLink]="['/details', housingLocation.id]">Learn More</a> // 点击后会把当前的id传过去
</section>

跳转到路由组件后,通过this.route.snapshot.params["id"]方式获取传过来的id值

import { Component, inject, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { HousingService } from "src/housing.service";
import { HousingLocation } from "../housingLocation/housinglocation";

@Component({
  selector: "app-details",
  templateUrl: "./details.component.html",
  styleUrls: ["./details.component.css"],
})
export class DetailsComponent implements OnInit {
  route: ActivatedRoute = inject(ActivatedRoute);
  housingService = inject(HousingService);
  housingLocation: HousingLocation | undefined;

  constructor() {
    const housingLocationId = Number(this.route.snapshot.params["id"]);
 // const housingLocationId = Number(this.route.snapshot.paramMap.get('id')); // 这样子也可以
    this.housingLocation = this.housingService.getHousingLocationById(housingLocationId); //通过id查找这个housinglocation的值(在其他文件里面写的方法)    
  }

  ngOnInit() {}
}

后面页面上就可以使用通过这个id找到的房屋信息啦!

补充:除了点击跳转外,常见的路由跳转方式还有编程式导航。比如在点击按钮、表单提交、登陆成功等场景下,我们就可以用Router服务进行跳转,示例如下:

import { Router } from '@angular/router';

@Component({...})
export class SomeComponent {
  constructor(private router: Router) {}

  goToProfile(id: number) {
    this.router.navigate(['/profile', id]);
  }
}

这里也列举几种路由跳转的示例:

this.router.navigate(['/dashboard']);           // 进入 dashboard
this.router.navigate(['../'], { relativeTo: this.route }); // 相对跳转
this.router.navigate(['/user', 42, 'edit']);    // 跳到 /user/42/edit
this.router.navigate(['/search'], { queryParams: { keyword: 'angular' } });  // 带参数跳转

今天暂时先写一下路由相关的,看了下官网,后面三个教学是讲表单的,放到下一part再总结。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值