1

I'm using ionic. I have a really basic question on actualizing data in component. I fetch data in components ngOnInit method over httpservice. This is only done once but it should be done every time this component is shown in view. What is the appropriated way to do this.

ngOnInit()
    myService.getData().subscribe(response => {
   
      }, error => {
        console.log(error);
      });
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
quma
  • 5,233
  • 26
  • 80
  • 146
  • Couple of quick questions, can you please share the implementation of `getData` method of `MyService`? and are you using Ionic framework (ionic has its own lifecycle hook eg. like `ionViewDidEnter()`? – Pankaj Parkar Jul 20 '22 at 05:40
  • Thanks Parkar, I use ionic und that did it! – quma Jul 20 '22 at 06:00

2 Answers2

1

Just call a method in subscribe.

ngOnInit() {
    myService.getData().subscribe(response => {
        this.someMethod(response);   // Add this line.
      }, error => {
        console.log(error);
      });
}

someMethod = (response) => {
  // Write your logic here that you have to do after you fetched your data.
}
N.F.
  • 3,844
  • 3
  • 22
  • 53
1

In Ionic ngOnInit won't call when the page is revisited. The reason is Ionic doesn't remove the components from the DOM once they are visited.

So Ionic does follow different sets of lifecycle hooks. You have to call ionViewDidEnter hook to call something on component init.

ionViewDidEnter() {
    myService.getData().subscribe(response => {
      }, error => {
        console.log(error);
      });
}
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299