Angular 2 - 实现UrlSerializer

时间:2017-04-13 19:07:26

标签: angular

我正在尝试实现自己的UrlSerializer类,这就是我所做的:

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", '-');
    }
}

当我尝试编译时,我得到以下错误:

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.

怎么了?

1 个答案:

答案 0 :(得分:6)

我会说问题是implements关键字。因为它期望一个没有实现的接口,所以你不能调用superUrlSerializer是一个抽象类,因此您可以使用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');

它应该有用。