路由到具有不同参数的同一 URL 后,页面上的数据未更新

Roh*_*mar 6 router routes angular angular-resolver

基本上我有一个通知组件,可以在单击标题中的图标时显示通知。当我们单击标题上的图标时,它会打开一个弹出窗口并显示通知列表。单击任何一个通知时,它会将用户路由到该特定通知的组件,就像单击 notification 一样,它将用户带到该路由:profile/guest/{guestid}/alerts/{alertid}。但是,当我们单击上述路线中的另一个通知时,它会更改路线参数,但不会重新加载新警报的数据,而仅显示旧路线的数据。

注意:显示的数据是从路由解析中获取的。由于组件已经加载,当我们单击另一个通知时,它不会调用 ngOnInit 或构造函数。但是当我们刷新页面时,它会根据更新的路线显示正确的数据。

我尝试实现不同的路由器配置解决方案来重新加载解析数据。例如 runGuardsAndResolvers 以及 onSameUrlNavigation。

我还尝试在其他角度组件生命周期挂钩(例如 ngAfterViewInit 或 ngAfterViewChecked)中调用设置数据的函数。

我又尝试了几种解决方案,但都没有用。

 Notification.component.ts :-(inside header component in shared module)
/**
   * * Callback when user clicks on visit button in notification modal
   * @param notification : notification 
   */
  navigateToGuestOrCustomer(notification: notification) {
    let routePath =
      notification.model == ALERT_MODEL.GUEST ? "guest" : "customers";
    let routeParamId = notification.detail_id;
    let alertId = notification.id;
    this.router.navigate([`/profile/${routePath}/${routeParamId}/alerts/${alertId}`]);
  }


edit-alert.component.ts(inside profile module in guest component>alert component)

  ngOnInit() {
    this.fetchRouteData();
    this.setGuestId();
    this.setGuestName();
  }

  /**
   * * get guest name from route resolve
   */
  setGuestName(): void {
    let guestData = this.route.parent.snapshot.data["editGuestInfo"];
    this.guestName = guestData["name"];
  }

  formData: any;
  alertListForGuest = [];
  /**Fetch Data from Resolve */
  fetchRouteData() {
    this.formData = this.route.snapshot.data["alertDetailForGuest"];
    this.alertListForGuest = this.route.snapshot.data["alertListForGuest"];
    this.alertListForGuest.push(this.formData.alert);
  }
Run Code Online (Sandbox Code Playgroud)

预期结果:单击其他通知后,路由参数应更改并显示包含更新数据的所需页面。

实际结果:仅改变路线,而不改变数据。

小智 6

ngOnInit如果仅更改路由,但不重新创建组件,则可能不会再次调用。您应该订阅路由更改并在那里执行获取和更新逻辑

import { ActivatedRoute } from '@angular/router`
constructor(private activatedRoute : ActivatedRoute){  }

ngOnInit() {
    this.activatedRoute.url.subscribe(url =>{
        // Code to get the new notification data 
        // and display it
    });
}
Run Code Online (Sandbox Code Playgroud)

这样当你导航到一个新的url时,代码会再次执行