【问题标题】:How to refresh a component on each page change如何在每个页面更改时刷新组件
【发布时间】:2016-06-07 20:45:39
【问题描述】:

我在 Angular 2 组件中调用数据服务以在 ngOnInit() 函数上加载数据。该组件放置在 Ionic 选项卡页面上。 ngOnInit() 函数仅在初始化时调用,而不是在每次导航到选项卡时调用。我想在每次导航到页面时从数据服务重新加载数据,以使用最新数据刷新组件。

如何在每次导航到标签页时调用组件中的函数?

这是我的组件:

@Component({
  selector: 'reservation-list',
  templateUrl: 'build/components/reservation-list.component.html',
  bindings: [DataService, TimeService]
})
export class ReservationListComponent {
  public items: any = [];

  constructor(private dataService: DataService) { }

  public ngOnInit() {
    // this I want to call on each tab navigation!
    this.items = this.dataService.getEvents();
  }
}

我的标签基本上是 ionic2-tabs 示例:

@Page({
  templateUrl: 'build/pages/tabs/tabs.html'
})
export class TabsPage {
  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any = Page1;
  tab2Root: any = Page2;
  tab3Root: any = Page3;
}

并且该页面是插入组件的基本离子页面:

<reservation-list></reservation-list>

@Page({
  templateUrl: 'build/pages/page1/page1.html',
  directives: [ReservationListComponent]
})
export class Page1 {

  constructor() {
  }
}

【问题讨论】:

    标签: javascript angular ionic2


    【解决方案1】:

    我认为您可以在单击选项卡并调用该函数时添加一个单击事件处理程序。

    在你的标签中

    <a (click)="getEvents()"></a>
    

    在你的组件中

    getEvents() {
        this.items = this.dataService.getEvents();
    }
    

    【讨论】:

    • 那我应该把 getEvents 放在哪里呢?在页面中?该页面对组件一无所知。
    • 你应该把两者都放进去。在您的 HTML 模板和组件中。
    • 如果这样做,是否需要将项目标记为输入参数? &lt;reservation-list [items]="items"&gt;&lt;/reservation-list&gt; ?
    • 否,因为您在预订列表组件中调用 getEvents 函数。所以你不需要项目输入
    【解决方案2】:

    请遵循离子的生命周期,并在标签子页面中使用以下方法。

    ionViewWillEnter()
    {
    //apply your code
    }
    

    当您进入页面时,此方法将始终调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 2020-02-08
      • 2016-09-24
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多