繁体   English   中英

检测在 Angular2 中按下的返回按钮

[英]Detect Back button pressed in Angular2

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

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();
        }
    );
}

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

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();
    }
}

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

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

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
        }
    }
}

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

在服务中创建一个变量,将其初始化为 false 并在 ngOnInit 方法中将其设置为 true。由于服务仅初始化一次,因此添加 ngOnInit :-

 ngOnInit(){
    if(!this._filterService.flag) this._filterService.clear()
  this._filterService.flag = true;
  //rest of your code
 }

确保服务只初始化一次,即当应用程序被引导而不是在组件的元数据内。如果页面被刷新,标志值最初为假,如果使用后退按钮访问组件为真

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM