Ahmed Shabib
Ahmed Shabib

Reputation: 697

Angular 2 Routing with params along with other string

I want to have following pattern in the route. Pattern:

"abc/test-:foo"

In Angular 2 I am getting

URL Cannot match any routes. URL Segment: 'abc/test-boo'

I have tried the same in AngularJs(1) it works fine, I am able to extract foo from stateParams.

Upvotes: 0

Views: 1036

Answers (2)

Ahmed Shabib
Ahmed Shabib

Reputation: 697

We solved it thanks gunter for pointing me to right class. Here is the code snippet

Define the pattern as

abc/test-/:foo

Then in the code

import {UrlSerializer, UrlTree, DefaultUrlSerializer} from "@angular/router";
import {Injectable} from "@angular/core";
@Injectable()
export class MySerializer implements UrlSerializer {
  defaultUrlSerializer: DefaultUrlSerializer;

  constructor() {
    this.defaultUrlSerializer = new DefaultUrlSerializer();
  }

  parse(url: string): UrlTree {
    url = url.replace("test-", "test-/");
    return this.defaultUrlSerializer.parse(url);

  }

  serialize(tree: UrlTree): string {
    return this.defaultUrlSerializer.serialize(tree).replace("test-/", "test-");
  }
}

Also make sure you have included this in the provider list

 providers: [{
      provide: UrlSerializer, useClass: MySerializer
    }
 ]

Upvotes: 0

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657118

:foo can't be a substring of a segment, a parameter needs to take the whole part like

abc/test-/:foo

You can implement a custom https://angular.io/docs/ts/latest/api/router/index/UrlSerializer-class.html to achieve that though.

Upvotes: 1

Related Questions