【问题标题】:Appending parameter by default to every route by default默认情况下将参数附加到每个路由
【发布时间】:2023-02-06 14:27:05
【问题描述】:

在我的角度应用程序中,路线定义如下。

const routes: Routes = [
  {
    path: ':lang',
    children:
      [
        { path: 'home', component: HomeComponent },
        { path: 'dashboard', component: DashboardComponent },
      ]
  },
]

其中 :lang 是应用程序显示的语言。申请网址是这样的http://localhost:4300/en/dashboard

现在,要从一条路线导航到另一条路线,每次都需要添加语言,因为它是父路线。 <a routerLink="en/dashboard">Dashboard</a>

默认情况下,有没有办法将 :lang 作为第一个参数添加到每个路由,这样子组件就不必担心在每个 url 导航之前附加 en

【问题讨论】:

    标签: angular angular-routing


    【解决方案1】:

    您可以使用 HTTP 拦截器。

    我添加了一个示例 HTTP 拦截器供您参考。

    import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
    import { Observable } from 'rxjs';
    
    @Injectable()
    export class CustomInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const newReq = req.clone({
          params: req.params.append('defaultParam', 'value')
        });
        return next.handle(newReq);
      }
    }
    

    然后添加创建的HTTP_INTERCEPTORS您的应用程序模块类中的提供程序。

    import { NgModule } from '@angular/core';
    import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
    
    // custom interceptor import here
    // import { CustomInterceptor } from 'custom.interceptor';
    
    @NgModule({
      imports: [
        HttpClientModule
      ],
      providers: [
        { provide: HTTP_INTERCEPTORS, useClass: CustomInterceptor , multi: true }
      ]
    })
    export class AppModule { }
    

    【讨论】:

      猜你喜欢
      • 2011-07-09
      • 2018-06-27
      • 2019-10-02
      • 1970-01-01
      • 2016-12-01
      • 2018-06-08
      • 2019-01-21
      • 2016-03-12
      • 1970-01-01
      相关资源
      最近更新 更多