2017-04-13 172 views
0

我想實現我自己的UrlSerializer類,這是我做的:角2 - 實施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. 

怎麼了?

回答

0

我會說問題是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'); 

它應該工作。

+0

UrlSerializer是一種抽象方法,現在我得到一個錯誤,我不能使用超級。我如何訪問默認的URL序列化器? – TheUnreal

+0

啊,是的,這是真的。你可以使用DefaultUrlSerializer https://angular.io/docs/ts/latest/api/router/index/DefaultUrlSerializer-class.html –

+0

謝謝!但我如何將它導入到我的自定義類中?沒有構造函數摘要 – TheUnreal