angular - Angular:如何仅在应用程序内部返回
问题描述
在 Angular 中返回上一页非常简单:
import {Component} from '@angular/core';
import {Location} from '@angular/common';
@Component({
// component's declarations here
})
class SomeComponent {
constructor(private _location: Location)
{}
backClicked() {
this._location.back();
}
}
这相当于点击浏览器的“后退”按钮。但是如何修改此代码,以便将您带到应用程序外部this._location.back()
的url ,而不是将您重定向到应用程序内部的路由。
例如,假设您在Google.com
,然后您粘贴my-app.com/page-foo
并以这种方式导航。this._location.back()
将带您回到Google.com
,但我希望它改为导航到my-app.com/page-bar
。
解决方案
在https://nils-mehlhorn.de/posts/angular-navigate-back-previous-page找到了答案。
1.制作一个新的navigation-service
:
import { Injectable } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { Location } from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class NavigationService {
private MAX_HISTORY_LEN = 10; // prevent history from growing indefinitely
private history: string[] = [];
constructor(private router: Router, private location: Location) {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.history.push(event.urlAfterRedirects);
if (this.history.length > this.MAX_HISTORY_LEN) {
this.history.shift();
}
}
});
}
back(): void {
this.history.pop();
if (this.history.length > 0) {
this.location.back();
} else {
this.router.navigateByUrl('/');
}
}
}
2.将服务注入app.component.ts
,以便跟踪整个应用程序的历史记录
export class AppComponent implements AfterViewInit {
constructor(private navigationService: NavigationService) {
}
...
3.(click)
然后在您想使用它的任何地方更新功能。使用原始示例:
@Component({
// component's declarations here
})
class SomeComponent {
constructor(private navigationService: NavigationService)
{}
backClicked() {
this.navigationService.back();
}
}
我从博文中做了一些调整:
- 添加了一个
MAX_HISTORY_LEN
以防止历史数组在整个应用程序使用过程中无限增长 - 注入
navigation-service
inapp.component.ts
以便它始终跟踪历史记录。如果您只在调用的组件中注入服务,.back()
那么在您第一次调用它时它可能没有历史记录。
推荐阅读
- azure - Azure 文件存储内容类型始终为 application/octet-stream
- liferay - Liferay 服务构建器最后一次修改
- php - 正则表达式不断返回 null
- python-3.x - 篮子联系没有重新开始
- c++ - C ++中的Tensorflow批量预测
- javascript - 在 Firebase Firestore 中,我想使用 orderBy 两次。我是否需要创建索引来加快查询速度?
- javascript - 为什么我不能为我的数组设置一个 css 属性。Hangman Javascript 的编码
- docker-compose - Hyperledger cli 容器不会将卷与主机绑定
- ios - 保存选项卡式应用程序中选项卡的用户重新排序
- entity-framework - 代码优先实体框架项目中自定义sql语句放在哪里