在Angular2中按下检测后退按钮

时间:2016-08-02 14:48:58

标签: javascript angularjs angular

我在尝试检测加载此组件时是否按下了后退按钮。在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();
        }
    );
}

2 个答案:

答案 0 :(得分:0)

在我的应用程序中,我创建了一个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()运算符,因为我注意到后退按钮导致NavigationStart事件被发送两次,第一个有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中。 Full details in this SO post.

答案 1 :(得分:-1)

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

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

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