Angular - 2 个组件具有相同的 URL
Angular - 2 components with same URL
我有一个要求,我需要对 2 个组件使用相同的 URL。
我们假设路径是 /path
,组件是 Foo
和 Bar
。
最初,我会看到 Foo 组件,然后按 link 我将被重定向到 Bar 组件。
/path (Foo) => /path (Bar)
现在我看到了 Bar 组件,如果我从浏览器中按下后退按钮,我需要被重定向到 Foo 组件
/path (Bar) =>back button=>/path (Foo)
此外,如果我按下 "forward" 按钮,我需要查看 Bar 组件
/path (Foo) =>forward button=> /path (Bar)
所以,基本上,我需要有相同的 URL 但不知何故保留 Angular 路由器提供的所有功能,就像有 2 条不同的路径一样。
这可能吗?我查看了 NavigationExtras 选项,例如 skipLocationChange
或 replaceUrl
,但这些选项对我没有帮助。 history
pushState
或 replaceState
也没有(或者我不知道如何使用它们)。
听起来您最好让一个父组件具有一个 url 路径,其中包含组件 foo
和 bar
,并有条件地显示一个或另一个,取决于 URL 中的查询参数。例如
toggleFooBar(){
this.showFoo = !this.showFoo;
this.router.navigate([],
{
relativeTo: this.activatedRoute,
queryParams: {showFoo : this.showFoo}
}
);
}
有关 url 参数的更多信息 here。
如果您订阅父组件中位置的更改(并相应地显示/隐藏 foo
或 bar
),前进和后退按钮应按要求工作:
ngOnInit() {
this.location.subscribe(queryParams => {
// Don't forget to unsubscribe on destroy
this.showFoo = (this.activatedRoute.snapshot.queryParams.showFoo !== 'true')
});
}
使用代码 here, but use this to see the forward / back buttons in action.
的实例
我认为如果不对 URL 进行一些更改,您将无法使用前进/后退按钮,因为 URL 必须更改才能使用是浏览器历史记录中要后退或前进的条目。
也许可以通过一些严肃的代码体操来接近...也许您可以使用查询参数然后再将它们取下?但即便如此,我认为您仍有可能导致浏览器/历史记录以意想不到的方式运行,这可能对您的应用程序弊大于利。
我有一个要求,我需要对 2 个组件使用相同的 URL。
我们假设路径是 /path
,组件是 Foo
和 Bar
。
最初,我会看到 Foo 组件,然后按 link 我将被重定向到 Bar 组件。
/path (Foo) => /path (Bar)
现在我看到了 Bar 组件,如果我从浏览器中按下后退按钮,我需要被重定向到 Foo 组件
/path (Bar) =>back button=>/path (Foo)
此外,如果我按下 "forward" 按钮,我需要查看 Bar 组件
/path (Foo) =>forward button=> /path (Bar)
所以,基本上,我需要有相同的 URL 但不知何故保留 Angular 路由器提供的所有功能,就像有 2 条不同的路径一样。
这可能吗?我查看了 NavigationExtras 选项,例如 skipLocationChange
或 replaceUrl
,但这些选项对我没有帮助。 history
pushState
或 replaceState
也没有(或者我不知道如何使用它们)。
听起来您最好让一个父组件具有一个 url 路径,其中包含组件 foo
和 bar
,并有条件地显示一个或另一个,取决于 URL 中的查询参数。例如
toggleFooBar(){
this.showFoo = !this.showFoo;
this.router.navigate([],
{
relativeTo: this.activatedRoute,
queryParams: {showFoo : this.showFoo}
}
);
}
有关 url 参数的更多信息 here。
如果您订阅父组件中位置的更改(并相应地显示/隐藏 foo
或 bar
),前进和后退按钮应按要求工作:
ngOnInit() {
this.location.subscribe(queryParams => {
// Don't forget to unsubscribe on destroy
this.showFoo = (this.activatedRoute.snapshot.queryParams.showFoo !== 'true')
});
}
使用代码 here, but use this to see the forward / back buttons in action.
的实例我认为如果不对 URL 进行一些更改,您将无法使用前进/后退按钮,因为 URL 必须更改才能使用是浏览器历史记录中要后退或前进的条目。
也许可以通过一些严肃的代码体操来接近...也许您可以使用查询参数然后再将它们取下?但即便如此,我认为您仍有可能导致浏览器/历史记录以意想不到的方式运行,这可能对您的应用程序弊大于利。