angularjs 如何在angular 16中检测页面是否刷新

bxjv4tth  于 6个月前  发布在  Angular
关注(0)|答案(1)|浏览(79)

我在angular 12中有一个代码可以正常工作,但在angular 16中不工作。
下面是我的代码:

this._router.events
        .pipe(filter((rs): rs is NavigationEnd => rs instanceof NavigationEnd))
        .subscribe(event => {
          if (event.id === 1 && event.url === event.urlAfterRedirects) {
            this.updateDetails();
          }
        })

字符串
我在模块的组件中实现了一个功能,它需要在刷新页面时调用一个函数。然而,目前,当页面刷新时,该函数不会执行。

mmvthczy

mmvthczy1#

由于你的标题描述了检测页面是否刷新,我建议下面的代码,如果你刷新页面,在一个服务上的变量名firstLoad被设置为false,那么路由器事件检查变量是否为false并调用相关的方法,然后将firstLoad设置为true,这将确保事件只在页面刷新时被触发!
服务项目:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class TestService {
  firstLoad = false;
  constructor() {}
}

字符串
main.ts

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import {
  RouterModule,
  NavigationEnd,
  Router,
  Event,
  provideRouter,
} from '@angular/router';
import { filter } from 'rxjs/operators';
import 'zone.js';
import { TestService } from './test.service';
import { TestComponent } from './test/test.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterModule],
  template: `
    <h1>Hello from {{ name }}!</h1>
    <a routerLink="../">
      back
    </a>
    <router-outlet></router-outlet>
  `,
})
export class App {
  name = 'Angular';

  constructor(private _router: Router, private testService: TestService) {}

  ngOnInit(): void {
    this._router.events
      .pipe(filter((rs): rs is NavigationEnd => rs instanceof NavigationEnd))
      .subscribe((event: Event) => {
        if (!this.testService.firstLoad) {
          this.testService.firstLoad = true;
          console.log('page refreshed');
        } else {
          console.log('normal');
        }
        // if (event.id === 1 && event.url === event.urlAfterRedirects) {
        //   this.updateDetails();
        // }
      });
  }
}

bootstrapApplication(App, {
  providers: [
    provideRouter([
      {
        path: 'test',
        component: TestComponent,
      },
      {
        path: '',
        redirectTo: 'test',
        pathMatch: 'full',
      },
    ]),
  ],
});


我在服务上定义的原因是因为只有在加载过程中这个变量才会为false,在事件运行后,它不可能被重置!
stackblitz

相关问题