繁体   English   中英

angular 2 在路由中排除 url

[英]angular 2 exclude url in routing

我已经使用 angular 实现了路由,如下所示 -

export const routes: RouterConfig = [
  { path: '', component: HomeComponent },
  { path: '**', component: SearchComponent }
];

我需要匹配所有要搜索的默认网址。 Angular 应用程序中有一些静态资源,如 js、css 文件。 我的问题是所有静态资源现在也将搜索组件。 有什么方法可以从路由中排除这些静态资源。

尝试这样的事情。 请注意,您需要在顶部导入所有其他模块,我假设您正在 app.module.ts 文件中设置路由。

这也使用了 Angular1.x 样式http://url/#/路由样式,因为我发现它在部署时在浏览器中更加稳定。

我还建议在部署目录的根目录下创建一个静态资产目录,并将静态文件存储在那里。 像这样的东西:

/static/
       /css/
       /js/
       /images/

import all modules...
import { RouterModule, Routes, PreloadAllModules } from '@angular/router';

const routes: Routes = [
  { path: '', 
    component: HomeComponent, 
    pathMatch: 'full'
   },
  { path: '**', 
    component: SearchComponent
  }
];

@NgModule({
  declarations: [
    HomeComponent,
    SearchComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes,
    {
      useHash: true,
      preloadingStrategy: PreloadAllModules
    }),
  ],
    bootstrap: [AppComponent]
})

export class AppModule {}

最简单的方法是使用UrlMatcher

新航线

const routes: Routes = [
  { path: '', 
    component: HomeComponent, 
    pathMatch: 'full'
   },

  { matcher: PathExcluding, component: SearchComponent },
];

在您的应用程序路由模块中添加此功能

export function PathExcluding(url: UrlSegment[]): any {
  return url.length === 1 && !(url[0].path.includes('url-Path-to-Exlude')) ? ({consumed: url}) : undefined;
}

您可以使用 url[0].path 对您的路径执行任何类型的字符串检查

帮助我的是将排除路径添加到 ngsw-config.json 中的 navigationUrls。

请参阅https://angular.io/guide/service-worker-config#matching-navigation-request-urls

虽然这些默认标准在大多数情况下都很好,但有时需要配置不同的规则。 例如,您可能想要忽略特定路由(不属于 Angular 应用程序的一部分)并将它们传递到服务器。

示例:

  ...
  "navigationUrls": [
    "/**", 
    "!/**/*.*", 
    "!/**/*__*", 
    "!/**/*__*/**", 
    "!/path_to_exclude/**"]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM