Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
996 views
in Technique[技术] by (71.8m points)

javascript - Detect Back button pressed in Angular2

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();
        }
    );
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...