Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 exclude url in routing

Tags:

angular

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.

like image 647
saurabh Avatar asked Sep 01 '16 12:09

saurabh


2 Answers

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 {}
like image 127
Stephen R. Smith Avatar answered Nov 07 '22 17:11

Stephen R. Smith


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

like image 40
Mhyland Avatar answered Nov 07 '22 15:11

Mhyland