0

I want to use a function that is defined in tab1.ts in the tabs.ts page.

tabs.ts --|
        --tab1.ts

I've declared the variable , but it gives me undefined when I call the function.

tabs.ts

tab1: Tab1Page;

  refreshData() {
    this.tab1.routerWatch();
  }

tab1.ts

routerWatch() {
    this.routerSubscription = this.router.events.subscribe(
      (event: NavigationEnd) => {
        if (event instanceof NavigationEnd) {
          if (event.url == '/tabs/tab1')
            console.log(event.url);
          this.authService.allPosts();
          this.posts$ = this.authService.posts$;
        }
      }
    );
  }

I want to refresh my data when the user clicks on the tab button 'home' , the problem is I cannot access the data from tabs page while the user is on the tab1 page

Robert Crx
  • 13
  • 2
  • duplicate, see https://stackoverflow.com/a/53689169/9217586 – Lys Feb 09 '21 at 01:16
  • Does this answer your question? [How to call child components's method from the parent component in Angular 6](https://stackoverflow.com/questions/53057340/how-to-call-child-componentss-method-from-the-parent-component-in-angular-6) – Sivakumar Tadisetti Feb 09 '21 at 02:10
  • the problem is.. i don't have components , I have pages.. and i cannot call the page since it's like an entire page , i just need something from it – Robert Crx Feb 09 '21 at 02:26

2 Answers2

0

The best approach for this case is using a service to share you data, this is a good example: Read the part called Sharing Data via Service https://medium.com/front-end-weekly/sharing-data-between-angular-components-f76fa680bf76#:~:text=In%20the%20parent%20component%2C%20we,it%20on%20a%20button%20click. #shared.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class SharedService {

  private message = new BehaviorSubject('First Message');
  sharedMessage = this.message.asObservable();

  constructor() { }

  nextMessage(message: string) {
    this.message.next(message)
  }
  
}
//parent.component.ts

import { Component, OnInit } from '@angular/core';
import { SharedService } from "../shared.service";

@Component({
  selector: 'app-parent',
  template: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  message:string;

  constructor(private sharedService: SharedService) { }

  ngOnInit() {
    this.sharedService.sharedMessage.subscribe(message => this.message = 
   message)
  }

}
vi calderon
  • 196
  • 1
  • 8
0

This is a very long answer that shows different ways of communicating a little crazy.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Guiditox
  • 657
  • 4
  • 10