4

I'm trying to implement my own UrlSerializer class, this is what I did:

import { UrlSerializer,UrlTree } from '@angular/router';

export class CustomUrlSerializer implements UrlSerializer {

    parse(url: string): UrlTree {
        // Change plus signs to encoded spaces
        url.replace("%20", '-');
        // Use the default serializer that you can import to just do the 
        // default parsing now that you have fixed the url.
        return super.parse(url)  
    }

    serialize(tree: UrlTree): string {
        // Use the default serializer to create a url and replace any spaces with + signs
        return super.serialize(tree).replace("%20", '-');
    }
}

When I'm trying to compile I get the following erros:

c:/xampp/htdocs/proj/src/app/custom-url-serializer.ts (11,12): 'super' can only be referenced in a derived class.
c:/xampp/htdocs/proj/src/app/custom-url-serializer.ts (16,12): 'super' can only be referenced in a derived class.

What's wrong?

1 Answer 1

10

I would say the problem is the implements keyword. Because it expect an interface, which has no implementation, so you cannot call super. The UrlSerializer is an abstract class, so you could use the DefaultUrlSerializer:

import { DefaultUrlSerializer, UrlTree } from '@angular/router';
class CustomUrlSerializer extends DefaultUrlSerializer {
    parse(url: string) : UrlTree {
        return super.parse(url);
    }
}
new CustomUrlSerializer().parse('http://stackoverflow.com');

It should work.

Sign up to request clarification or add additional context in comments.

5 Comments

UrlSerializer is an abstract method, now I get an error that I can't use super. How I can access the default url serializer?
Ah, yes, that's true. You can use DefaultUrlSerializer angular.io/docs/ts/latest/api/router/index/…
Thanks! But how I can import it to my custom class? there is no constructor for abstracts
I'm not sure what you exactly mean, but I edited my answer to include more code and the DefaultUrlSerializer. I tried that example and it worked well.
In case anyone is still wondering: you should add it to your root app module providers, e.g. @NgModule({ providers:[{provide: UrlSerializer, useClass: CustomUrlSerializer }, /*more providers*/], /*bootstrap etc*/ }) export class myApp { /*etc*/ }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.