saurabh
saurabh

Reputation: 2459

angular 2 exclude url in routing

I have implemented routing using angular as below -

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

I need to match all the default urls to search. There are some statics resources like js, css files in angular application. My problem is that all the static resources are also going to search component now. Is there some way I can exclude these static resources from routing.

Upvotes: 8

Views: 8781

Answers (3)

Hendrik
Hendrik

Reputation: 61

What helped me was adding the path te exclude to navigationUrls in ngsw-config.json.

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

While these default criteria are fine in most cases, it is sometimes desirable to configure different rules. For example, you may want to ignore specific routes (that are not part of the Angular app) and pass them through to the server.

Example:

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

Upvotes: 0

Mhyland
Mhyland

Reputation: 280

The simplest way to do this is with a UrlMatcher.

New routes

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

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

Add this function in your app-routing module

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

you can use url[0].path to perform any kind of string checking for your path

Upvotes: 1

Stephen R. Smith
Stephen R. Smith

Reputation: 3400

Try something like this. Note that you need to import all your other modules at the top, and I'm assuming that you're setting up routes in your app.module.ts file.

This also is using the Angular1.x style http://url/#/ routing style as I've found that to be much more stable in browsers when deployed.

I would also recommend create a static assets directory at the root of your deployment directory and store static files there. Something like this:

/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 {}

Upvotes: 2

Related Questions