本文介绍了Angular 2-实作UrlSerializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

怎么了?

推荐答案

我会说问题出在implements关键字上.因为它需要一个没有实现的接口,所以您不能调用super. UrlSerializer是一个抽象类,因此您可以使用DefaultUrlSerializer:

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');

应该可以.

这篇关于Angular 2-实作UrlSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-02 22:23