angular 路由及自定义路由

angular 路由及自定义路由,第1张

创建

1 在ng new xxx时,可以选择路由模块
2 通过 ng new routing-app --routing --defaults创建带有路由的应用 如下所示

基本配置

自定义路由的配置

routing-moudle模块

import { NgModule } from '@angular/core';
import { RouterModule, Routes, UrlSegment } from '@angular/router';
import { ProfileComponent } from './profile/profile.component';

const routes: Routes = [
  {
    matcher: (url) => {
      if (url.length === 1 && url[0].path.match(/^@[\w]+$/gm)) {
        return {
          consumed: url,
          posParams: {
            username: new UrlSegment(url[0].path.substr(1), {})
          }
        };
      }

      return null;
    },
    component: ProfileComponent
  }

];

 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

组件

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css'],
})
export class ProfileComponent implements OnInit {
  username$ = this.route.paramMap.pipe(
    map((params: ParamMap) => params.get('username'))
  );
  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {}
}

组件的html

<p>Hello {{username$ | async}}</p>

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/940695.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-17
下一篇2022-05-17

发表评论

登录后才能评论

评论列表(0条)

    保存