angular - 路由到具有不同参数的相同 url 后,页面上的数据未更新

标签 angular routes router angular-resolver

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

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

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

我还尝试在其他 Angular 组件生命周期 Hook (例如 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);
  }

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

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

最佳答案

如果仅路由更改,则可能不会再次调用 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
    });
}

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

关于angular - 路由到具有不同参数的相同 url 后,页面上的数据未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55707231/

相关文章:

javascript - 在 Angular 的子组件中单击按钮时如何将值设置为父组件属性

ruby-on-rails - 用户资源扩展

java - Spring Restful API,是否有像路由器一样使用方法来获取其他方法的端点或URL?

ruby-on-rails - 传递与 id 不同的参数以返回 JSON 用户对象的正确 Rails 路由是什么?提供 Controller 方法

c++ - P2P最重要的基础知识

javascript - Angular 2+ : Internet Explorer: Unable to get property 'call' of undefined or null reference

javascript - Angular 2 twitter Bootstrap sidemenu不折叠

javascript - 在 HTML 上显示 AngularFireList 数据时出现错误

angular - 无法匹配任何路线 angular 2.0.1

javascript - 如何使用 Backbone javascript 路由器?