如何在angular网站中使用第一个路径段作为参数



我有一个简单的角度应用程序。该网站的唯一功能是加载配置,并根据从路径中的第一个片段中抓取的名称设置一些图像和链接。我曾尝试设置路径,但在中没有成功

const routes =
[
{ path: '*', component: MyComponent }
];
RouteModule.forRoot(routes). 

路径类似https://mydomain.com/codehere

MyComponent使用此代码获取路径。

const locator=window.location.pathname.split('/'(.pop((;

定位器应="codehere">

我想解析字符串的codehere部分,并将其用作查询配置数据的键。它认为它在当地工作,但可能不是。我现在可以确认它在当地有效。我得到404个错误,没有找到任何组件。

我希望它在服务器上也能正常工作

您只需创建一个如下的路由,其中第一个参数将在激活的路由中可用,您所需要做的就是订阅它并执行您的逻辑

主页.ts

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { ActivatedRoute, Params } from '@angular/router';
import { Subscription } from 'rxjs';
@Component({
selector: 'home',
template: `
<div>
<h1>Current Route Path</h1>
<h3>Path: {{currentRouteParam}}</h3>
</div>
`,
})
export class HomeViewComponent implements OnInit, OnDestroy {
subscription: Subscription = new Subscription();
currentRouteParam;
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.params.subscribe((params: Params) => {
this.currentRouteParam = params.path;
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}

app.routing.module

import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { LoginViewComponent } from './views/login/login.component';
import { HomeViewComponent } from './views/home/home.component';
import { CatalogViewComponent } from './views/catalog/catalog.component';
@NgModule({
declarations: [LoginViewComponent, HomeViewComponent, CatalogViewComponent],
imports: [
RouterModule.forRoot([{ path: ':path', component: HomeViewComponent }]),
],
exports: [RouterModule],
providers: [],
})
export class AppRoutingModule {}

分叉堆叠式

最新更新