5

基本上我有一个通知组件,它在单击标题中的图标时显示通知。当我们单击标题上的图标时,它会打开一个弹出窗口并显示通知列表。单击任何通知时,它将用户路由到该特定通知的组件,例如单击通知时,它将用户带到该路由: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);
  }

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

实际结果:只有路线发生变化,数据没有变化。

4

3 回答 3

4

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 时,代码会再次执行

于 2019-04-16T12:31:01.227 回答
0

不知道为什么没有人提到,ActivatedRoute.data因为这正是它的用途

此路由的静态和解析数据的可观察值。

所以我通常会做这样的事情:

ngOnInit()
{
    this.activatedRoute.data.pipe(takeUntil(this.destroyed)).subscribe(data =>
    {
        // data is your resolved data 
        this.model.page = data.page;
        this.model.options = data.options;
    });
}

此代码将针对初始数据和更新数据运行,因此您可以删除您已有的任何使用activatedRoute.snapshot.data.

用inside完成this.destroyed的 a在哪里。Subject<void>this.destroyed.next()ngOnDestroy()

于 2021-10-07T00:10:07.120 回答
0

正如您所说,它在页面刷新后显示新数据,因此在这种情况下,只需尝试在同一页面上实现Route Reload以便它重新加载当前路由并获取新数据。

于 2019-04-16T12:31:34.217 回答