【问题标题】:angular 2 exclude url in routingangular 2在路由中排除url
【发布时间】:2016-09-01 12:06:36
【问题描述】:

我已经使用下面的角度实现了路由 -

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

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

【问题讨论】:

  • 你找到解决办法了吗?
  • @Gerardlamo ,我找不到解决方案。但后来 Angular 提出了“Routing Guard”功能。我认为我们可以使用警卫来处理这个问题。您可以在angular.io/docs/ts/latest/guide/router.html#!#guards 了解更多信息
  • 您找到解决方案了吗?
  • 当您说静态资源时,您是指组件的模板和 css 文件吗?您还有哪些其他静态资源?您是在组件级别还是在 index.html 文件中包含资源?

标签: angular


【解决方案1】:

试试这样的。请注意,您需要在顶部导入所有其他模块,并且我假设您正在 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 {}

【讨论】:

    【解决方案2】:

    最简单的方法是使用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 对您的路径执行任何类型的字符串检查

    【讨论】:

      【解决方案3】:

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

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

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

      例子:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-24
        • 1970-01-01
        • 2017-11-10
        • 1970-01-01
        • 1970-01-01
        • 2016-08-31
        • 2017-07-23
        • 1970-01-01
        相关资源
        最近更新 更多