2016-01-13 49 views
1

我們如何擴展或使用核心指令,服務,類的相同定義以及少量新功能?如何擴展Angular2的任何Core指令,服務,類?

比方說,我們要創造新的routerLink指令,它只有幾個事件listerner屬性和它的類更多的方法。

還有一件事,當我試圖這樣做或試圖啓動,

從angular.io我在GitHub上「https://github.com/angular/angular/blob/2.0.0-beta.1/modules/angular2/src/router/router_link.ts#L6-L84」這個參考。

但是當我試圖在本地下載的文件中找到相同的文件時,發現路徑上沒有這樣的文件(angular2/src/router/router_link.ts)。

雖然存在文件angular2/src/router/router_link.d.ts但它的內容與github源相比是不同的。

任何人都可以提供guidline同樣也擴展或重新創建自己的指令在CORE上?

回答

1

大部分服務/組件/ etc都可以很容易地擴展。

我延長RouterOutlet允許我用我自己的身份驗證服務,我注入了新的出路:

import {Directive, Attribute, ElementRef, DynamicComponentLoader, Inject} from 'angular2/core'; 
import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router'; 
import {UserService} from '../../services/user_service'; 
//import {LoginCmp} from '../login/login'; 

@Directive({ 
    selector: 'router-outlet' 
}) 
export class LoggedInRouterOutlet extends RouterOutlet { 
    public user: any; 
    private parentRouter: Router; 

    constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader, 
       _parentRouter: Router, @Attribute('name') nameAttr: string, @Inject(UserService) user:UserService) { 
    super(_elementRef, _loader, _parentRouter, nameAttr); 
    this.user = user; 
    this.parentRouter = _parentRouter; 
    } 

    activate(instruction: ComponentInstruction) { 
    var url = instruction.urlPath; 
    if (!this.user.publicRoutes[url] && !this.user.isAuth()) { 
     // todo: redirect to Login, may be there a better way? 
    console.log('Component Redirecting from:', url); 
     this.parentRouter.navigate([this.user.baseRoute]); 
    } 
    return super.activate(instruction); 
    } 
} 

原來是here from Auth0但有點過時與α/β開關

作爲源代碼,我認爲你正在尋找這是寫在打字稿

預編譯的代碼,當你從NPM得到它或者它已經通過編譯器運行。

希望有所幫助。

+0

丹尼斯,這不適用於RC4(於2016年6月30日發佈)。如何得到這個版本的工作? –

+1

@SatishMadiwal我沒有機會看看RC4,但哪部分不適合你?擴展名或路由器代碼?新路由器與我給出的例子截然不同。如果你試圖保護路線繼承人一個很好的教程:http://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html –

+0

是的,我已經跟隨這從angular.io網站:[CanActivate Guarding](https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard)。該類需要按照canActivate指南進行重寫。我今天能夠做到這一點。謝謝! –