2016-08-25 62 views
0

在角2 RC5路由器3.0.0 RC1我想從相同的組分(相同的文件或至少)內調用函數canDeactivate路由器檢查含義:寫CanDeactivate功能

{ path: 'componentPath', component: MyComponent, canDeactivate: [CanDeactivateGuard] } 

隨着CanDeactivateGuard而無論是在同一個文件MyComponent,或者甚至更好,CanDeactivateGuard可能是MyComponentcanDeactivate()功能在裏面MyComponent(但我不知道這是可能的)

我已經試過以下航線:

{ path: 'componentPath', component: MyComponent, canDeactivate: [MyComponent] } 

而且在MyComponent

import {Component, OnInit} from '@angular/core'; 
import { CanDeactivate } from '@angular/router'; 

@Component({ 
    selector: 'my-component', 
    providers: [], 
    templateUrl: 'MyComponent.html', 
    directives: [] 
}) 

export interface CanDeactivateComponent { 
    canDeactivate:() => boolean | Observable<boolean>; 
} 


export class MyComponent implements OnInit, CanDeactivate<CanDeactivateComponent> { 

    onInit(){ 
     // MyComponent initialization 
    } 

    canDeactivate(component: CanDeactivateComponent): Observable<boolean> | boolean { 
     console.log('test'); 
     return true; 
    } 


} 

但我發現了以下錯誤:

index:2 Error: Error: Can't resolve all parameters for MyComponent: (?, ?) 
+0

你找到了一個解決方案? –

回答

0

你可以從實施CanDeactivate'@角/路由器

canDeactivate(component: MyComponente, route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 
    return true; 
} 

我做nt認爲你需要在路由器配置中的canDeactivate,如果你這樣做。

重要編輯:這是RC5,我不知道它是否也能在RC1

+0

對不起,我還不夠清楚......我使用角度RC5和路由器RC1!我會稍後嘗試一下 – ncohen

+0

你可以更清楚地知道如何做到這一點嗎?我應該怎樣在'canDeactivate'中調用組件,而這個功能應該在組件內? – ncohen

0

我知道這是耗時的,但儘管如此,升級到RC.5和使用路線警衛。我描述了他們在這個博客(它使用RC4):https://yakovfain.com/2016/07/20/angular-2-guarding-routes/

從博客的代碼示例的RC.5版本是在這裏: https://github.com/Farata/angular2typescript/tree/master/chapter3/router_samples/app

+0

對不起,我還不夠清楚...我使用角度RC5和路由器RC1!我試圖以不同的方式使用警衛,請看這個問題 – ncohen