再次路由到同一组件时,不会调用ngOnInit-Angular 2

问题描述:

我正在使用angular 2 webapp,当数组中有数据并将其存储在service组件中时,我导航到xyz组件.xyz组件的ngOnInit()方法从服务获取数据并将其显示到其html模板.问题是,当我的源数组数据发生更改时,我将再次重定向到xyz组件,但是xyz的ngOnInit()方法这次不会被调用.有什么办法可以做到这一点?

I'm working on angular 2 webapp, I navigate to xyz component when I have data in my array and stores it in service component. The xyz component's ngOnInit() method get data from service and displays it to its html template. The problem is that when my source array data changes I'm redirecting to xyz component again but then xyz's ngOnInit() method does not get invoked this time. Is there any way to achieve this ?

您可以订阅组件中的事件.我不知道如何将其集成到您的代码中,但是在我看来,它是这样的:

You could subscribe to an event in your component. I don't know how to integrate this to you code, but on mine it looks like this :

ngOnInit() {
    this._events.xyz.onDataChange.subscribe (() => {
        this.onDataChange();
    }
onDataChange() {
    // Display to HTML Template
}

然后,当您的数据更改时,您将使用 this._events.xyz.onDataChange().publish()

And then, when your data changes, you use this._events.xyz.onDataChange().publish()

我正在使用TypeScript类EventsManager,您可能可以通过angular事件来执行此类操作.

I'm using a TypeScript class EventsManager, you can probably do this kind of things with angular's events.

不过,您应该等待经验丰富的开发人员的回答.

You should wait for answers from more experienced developers though.