问题是组件在导航时被重新初始化。因此,fromBackButton 字段在返回时设置为 true,并在新组件初始化时立即重置为 false。
所以你需要创建一个服务来获得在导航周期中“存活”的东西。我的意思是这样的:
import {Injectable, OnDestroy} from '@angular/core';
import {Location} from '@angular/common';
import {SubscriptionLike} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class NavigationStateService implements OnDestroy {
private _isFromBackButton = false;
private locationSubscription: SubscriptionLike;
constructor(private location: Location) {
this.locationSubscription = this.location.subscribe((popStateEvent: PopStateEvent) => {
// Detect popstate
if (popStateEvent.type === 'popstate') {
console.debug('fromBackButton NavigationStateService', popStateEvent);
this._isFromBackButton = true;
}
});
}
get isFromBackButton(): boolean {
return this._isFromBackButton;
}
clearFromBackButtonState() {
this._isFromBackButton = false;
}
ngOnDestroy(): void {
this.locationSubscription.unsubscribe();
}
}
对应的组件示例:
import {Component, OnInit} from '@angular/core';
import {NavigationStateService} from '../navigation-state.service';
@Component({
selector: 'app-page1',
templateUrl: './page1.component.html',
styleUrls: ['./page1.component.css']
})
export class Page1Component implements OnInit {
fromBackButton = false;
constructor(private navigationStateService: NavigationStateService) { }
ngOnInit(): void {
this.fromBackButton = this.navigationStateService.isFromBackButton;
this.navigationStateService.clearFromBackButtonState();
}
}
但是 PopState Event 的美中不足的是:它在向前和向后导航时被同等地触发。但那是另一项任务。这可能是一个很好的起点:How do I retrieve if the popstate event comes from back or forward actions with the HTML5 pushstate?