我正在使用Nativescript + Angular实现文件浏览器组件。
NativeScript 5.2.0-2019-01-18-12822
nativescript-angular 7.1.0
我有一条带有path参数的路由和一个目录视图组件,当用户点击文件系统层次结构时会递归调用该目录视图组件。
路线条目:
{ path: "debugfilebrowserdir/:path", component: DebugFileBrowserPageComponent }
我正在使用可观察的模式在ngOnInit()中的ActivatedRoute上订阅paramMap:
this.route.paramMap.subscribe( ( params ) => {
let path = params.get( 'path' );
// update the model with the entries from path
});
这就像冠军。我可以点击目录条目,然后更新视图。
我在ActionBar中有后退按钮:
<ActionBar class="action-bar" title="Files">
<NavigationButton android.systemIcon="ic_menu_back" text="Back" (tap)="goBack()"></NavigationButton>
</ActionBar>
一旦用户单击进入子目录,当有人单击操作栏上的后退按钮时,我想显示父目录。我可以用一个单独的按钮来完成此操作,但是看起来很混乱。
问题是,无论我在目录树中的深度如何,点击后退按钮时,它都将我带回到根组件而不是上一个视图。我猜这是因为每次显示子目录时,都会重复使用我的目录视图组件。 (验证为ngOnInit不会再次调用。)
我的想法是必须有某种方法可以动态地将条目推入历史记录堆栈或使我的目录视图组件被多次创建,但到目前为止我还没有发现任何东西。
有没有一种方法可以操纵导航历史记录堆栈,以便在点击“后退”按钮时可以重新显示具有不同参数的相同组件(即,在这种情况下,使用父目录的路径显示相同组件) ?
一个未解决的相关问题I have an issue with "history back" when navigate to same page
答案 0 :(得分:2)
您要做的是使用CustomRouteReuseStrategy
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot } from '@angular/router';
import { NSLocationStrategy } from 'nativescript-angular/router/ns-location-strategy';
import { NSRouteReuseStrategy } from 'nativescript-angular/router/ns-route-reuse-strategy';
@Injectable()
export class CustomRouteReuseStrategy extends NSRouteReuseStrategy {
constructor(location: NSLocationStrategy) {
super(location);
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return false;
}
}
,然后在您的AppModule中将其作为提供程序
import { NgModule, NgModuleFactoryLoader, NO_ERRORS_SCHEMA } from "@angular/core";
import { RouteReuseStrategy } from "@angular/router";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { AppRoutingModule } from "./app-routing.module";
import { CustomRouteReuseStrategy } from "./custom-router-strategy";
import { AppComponent } from "./app.component";
@NgModule({
bootstrap: [
AppComponent
],
imports: [
NativeScriptModule,
AppRoutingModule
],
declarations: [
AppComponent
],
providers: [
{
provide: RouteReuseStrategy,
useClass: CustomRouteReuseStrategy
}
],
schemas: [
NO_ERRORS_SCHEMA
]
})
export class AppModule { }
这是play.nativescript.org中的一个例子
https://play.nativescript.org/?template=play-ng&id=AspHuI
(我没有做这个,我只是在传递我学到的信息。)
此外,如果您只希望某些页面重用路由策略,则需要进行其他代码更改
shouldReuseRoute(future: ActivatedRouteSnapshot, current: ActivatedRouteSnapshot): boolean {
// first use the global Reuse Strategy evaluation function,
// which will return true, when we are navigating from the same component to itself
let shouldReuse = super.shouldReuseRoute(future, current);
// then check if the noReuse flag is set to true
if (shouldReuse && current.data.noReuse) {
// if true, then don't reuse this component
shouldReuse = false;
}
然后可以将noReuse用作路由参数,以便除了默认的“ shouldReuse”之外还要进行其他检查
希望这会有所帮助!