Angular 2 - 实现UrlSerializer

The*_*eal 2 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", '-');
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

怎么了?

Ján*_*aša 7

我会说问题是implements关键字.因为它期望一个没有实现的接口,所以你无法调用super.这UrlSerializer是一个抽象类,所以你可以使用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');
Run Code Online (Sandbox Code Playgroud)

它应该工作.

  • 万一有人还在想:你应该把它添加到你的根应用模块提供商,例如@NgModule({providers:[{provide:UrlSerializer,useClass:CustomUrlSerializer},/*more providers*/],/*bootstrap etc*/})导出类myApp {/*etc*/} (3认同)