Angular 2 - Implement UrlSerializer

2020-07-24 04:24发布

问题:

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:

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.



标签: angular