2017-08-07 26 views
0

我有幾條通往同一組件(即/ projects,/ projects/create,/ projects /:id和children,都指向我的ProjectComponent)的路線。 當在/ projects /:id之間導航時,只用:id改變了一切正常,我可以訂閱params並相應地更新我的內容,但是當我從/ projects導航到/ projects/create或/ projects /:id時,組件被重新創建。Angular 2/4:如何在不重新創建組件的情況下更改路線

有沒有什麼辦法可以導航到指向同一個組件的路徑而不重新創建?

+1

的【如何重定向到從angular2路線外部URL沒有成分?]可能的複製(https://stackoverflow.com/questions/40150393/how-to-redirect-to-an-外部url-from-angular2-route-without-using-component) – k11k2

回答

0

你應該實現自定義RouteReuseStrategy

創建服務實施RouteReuseStrategy

export class CustomReuseStrategy implements RouteReuseStrategy { 

    handlers: {[key: string]: DetachedRouteHandle} = {}; 

    shouldDetach(route: ActivatedRouteSnapshot): boolean { 
     return true; 
    } 

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void { 
     this.handlers[route.routeConfig.path] = handle; 
    } 

    shouldAttach(route: ActivatedRouteSnapshot): boolean { 
     return !!route.routeConfig && !!this.handlers[route.routeConfig.path]; 
    } 

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { 
     if (!route.routeConfig) return null; 
     return this.handlers[route.routeConfig.path]; 
    } 

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { 
     return future.routeConfig === curr.routeConfig; 
    } 
} 

並添加此供應商到@NgModule

providers: [ 
    {provide: RouteReuseStrategy, useClass: CustomReuseStrategy} 
] 

您可以調整CustomReuseStrategy只有某些路徑可以重用組件,但我會留給你o找出如何。

source

+0

感謝它是完美的,我實際上遇到這篇文章,但我駁斥它,因爲整個附加/分離/存儲/檢索的東西不是我一直在尋找。我需要多加關注。 –

相關問題