检测在 Angular2 中按下的返回按钮 [英] Detect Back button pressed in Angular2

查看:22
本文介绍了检测在 Angular2 中按下的返回按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检测加载此组件时是否按下了后退按钮.在 ngOnInit() 中,我想知道是否单击了 Back,因此我没有清除所有过滤器.代码如下:

导出类 ProductListComponent 实现 OnInit、OnDestroy {构造函数(私有_productsService:ProductsService,参数:RouteParams,私有_categoriesService:CategoriesService,私有_filtersService:FiltersService,私有_router:路由器,私有_location:位置){this.category = params.get('name') ?params.get('name') : null;}订阅:任何;类别:任何;加载:布尔值 = 假;页数:编号 = 1;计数:数量;产品:任何;页数:数组 = [];错误消息:字符串;ngOnInit() {this.getProducts();//如果(没有使用后退按钮){//this._filtersService.clear();//}this.subscription = this._filtersService.filterUpdate.subscribe((过滤器)=>{this.page = 1;var params = this.category ?{名称:this.category}:{};this._router.navigate([this.currentRoute, params]);this.getProducts();});}

解决方案

在我的应用程序中,我创建了一个 NavigationService,其中包含一个标志,可用于确定是否按下了后退按钮.

import { Injectable } from '@angular/core';从@angular/router"导入{路由器,导航开始};从'rxjs/operators'导入{tap, filter, pairwise, startWith, map };@Injectable({提供在:'根'})导出类导航服务{wasBackButtonPressed = false;构造函数(私有_路由器:路由器){this._router.events.pipe(过滤器(ev => ev instanceof NavigationStart),地图(ev =>  ev),开始(空),成对(),点击(([ev1, ev2]) => {if (!ev1 || (ev2.url !== ev1.url)) {this.wasBackButtonPressed = ev2.navigationTrigger === 'popstate';}})).订阅();}}

它使用 Rxjs pairwise() 运算符,因为我注意到后退按钮导致 NavigationStart 事件被发送 2 次,第一个具有 navigationTrigger = 'popstate' 而这正是我们正在寻找的.

现在我可以将这个服务注入到我的组件中,如果用户通过浏览器的后退按钮到达那里,我可以引用这个标志来确定是否运行特殊逻辑.

import { Component, OnInit } from '@angular/core';从 'src/services/navigation.service' 导入 { NavigationService };@成分({选择器:'应用程序示例',templateUrl: './app-example.component.html',styleUrls: ['./app-example.component.scss']})导出类 ExampleComponent 实现 OnInit {构造函数(私有_navigationService:NavigationService){}ngOnInit(): 无效 {如果(this._navigationService.wasBackButtonPressed){//当用户通过后退按钮导航时的特殊逻辑}}}

要知道的另一件事是,这个 NavigationService 应该在应用启动时立即运行,这样它就可以开始处理第一个路线变化.为此,请将其注入到您的根 app.component 中.此 SO 帖子中的完整详细信息.

I'm trying to detect if the back button was pressed when I load this component. In the ngOnInit(), I'd like to know if Back was clicked so I don't clear all my filters. Here is the code:

export class ProductListComponent implements OnInit, OnDestroy {
constructor (private _productsService: ProductsService, params: RouteParams, private _categoriesService: CategoriesService, private _filtersService: FiltersService, private _router: Router, private _location: Location) {
    this.category = params.get('name') ? params.get('name') : null;
}

subscription: any;
category: any;
loading: boolean = false;
page: number = 1;
count: number;
products: any;
pages: Array = [];
errorMessage: string;

ngOnInit() {

    this.getProducts();

    //if(back button wasnt used) {
    //    this._filtersService.clear();
    //}

    this.subscription = this._filtersService.filterUpdate.subscribe(
        (filters) => {
            this.page = 1;
            var params = this.category ? {name: this.category} : {};
            this._router.navigate([this.currentRoute, params]);
            this.getProducts();
        }
    );
}

解决方案

In my application I created a NavigationService which contains a flag that can be used to determine if the back button has been pressed.

import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { tap, filter, pairwise, startWith, map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class NavigationService {
    wasBackButtonPressed = false;

    constructor(private _router: Router) {
        this._router.events.pipe(
            filter(ev => ev instanceof NavigationStart),
            map(ev => <NavigationStart>ev),
            startWith(null),
            pairwise(),
            tap(([ev1, ev2]) => {
                if (!ev1 || (ev2.url !== ev1.url)) {
                    this.wasBackButtonPressed = ev2.navigationTrigger === 'popstate';
                }
            })
        ).subscribe();
    }
}

It is using Rxjs pairwise() operator because I noticed that back button causes NavigationStart event to be sent 2 times, the first one has navigationTrigger = 'popstate' and that is what we're looking for.

Now I can inject this service into my component, and I can reference this flag to determine whether to run special logic if the user arrived there via the browser's back button.

import { Component, OnInit } from '@angular/core';
import { NavigationService } from 'src/services/navigation.service';

@Component({
    selector: 'app-example',
    templateUrl: './app-example.component.html',
    styleUrls: ['./app-example.component.scss']
})
export class ExampleComponent implements OnInit {

    constructor(private _navigationService: NavigationService) {
    }

    ngOnInit(): void {
        if (this._navigationService.wasBackButtonPressed) {
            // special logic here when user navigated via back button
        }
    }
}

One other thing to know is, this NavigationService should run immediately at app startup, so it can begin working on the very first route change. To do that, inject it into your root app.component. Full details in this SO post.

这篇关于检测在 Angular2 中按下的返回按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆