2.0.0 • Published 2 years ago

ngx-advanced-router v2.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

ngx-advanced-router

Npm package version Npm package license Npm downloads total

GitHub latest commit

Example

Example code available here

Usage

  1. Install the package:
npm install --save ngx-advanced-router
  1. Create a service that extends AdvancedRouteService. This is where you'll supply your routes.\ While the default Angular router only allows paths to be supplied as strings, ngx-advanced-router allows paths to be supplied as either strings OR or functions.
// ...
import { AdvancedRouteService } from 'ngx-advanced-router';

@Injectable({
  providedIn: 'root',
})
export class YourAdvancedRouteService extends AdvancedRouteService {
  public readonly routesConfig = {
    somePath: {
      path: 'some-path', // Regular string path
      component: SomeComponent,
    },
    someDetailPath: {
      path: (id: string) => `some-path/${id}`, // Function-generated string path
      component: SomeDetailComponent,
    }
    // ...
    fallBack: {
      path: '**',
      redirectTo: 'some-path',
    },
  };
}
  1. Import the AdvancedRouteModule into your AppModule (or AppRoutingModule) using the forRoot() method, and pass in your advanced route service class.\
// ...
import { AdvancedRouterModule } from 'ngx-advanced-router';
import { RouterModule } from '@angular/router';
import { YourAdvancedRouteService } from './services/your-advanced-route.service';

@NgModule({
  // ...
  imports: [
    AdvancedRouterModule.forRoot(YourAdvancedRouteService),
  ],
})
export class AppModule {} // or AppRoutingModule
  1. Import the route service into any places where you need to access route paths.
// ...
import { YourAdvancedRouteService } from './services/your-advanced-route.service';
import { LazyLoadedRouteService } from './modules/lazy-loaded/services/lazy-loaded-route.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {

  constructor(
    // ...
    protected yourAdvancedRouteService: YourAdvancedRouteService,
    private router: Router,
  ) {}

  // ...
}

You can then use it inside a function:

  navigateToSomePath(): void {
    const somePath = this.yourAdvancedRouteService.routes.somePath.path;
    this.router.navigate([somePath]);
  }

Or in a routerLink in the HTML:

  <a [routerLink]="yourAdvancedRouteService.routes.somePath.path">

License

MIT