Search code examples
angularangular-ui-routerangular-router

Reload component when router-link visited


I need to call the ngOnInIt method each time the routerLink is visited, because I am using the ID in the currently visited link to bind and retrieve data from a database and if the method is not called I lose that data.

Here is an example of my init method (sorry don't know how to use code snippets here)

ngOnInit() {
    this.authService.getAuth().subscribe(auth=> {
        if(auth) {
            this.loggedInUser = auth.email;
        } else {
        }
    });

    this.teamService.getTeams().subscribe(teams => {
        this.teams = teams;
        console.log(this.teams);
        for(var i = 0; i < this.teams.length; i++) {
            if(this.teams[i].createdBy == this.loggedInUser) {
                this.myTeams.push(this.teams[i]);
            }
        }    
    });

    console.log(this.myTeams);

    this.id = this.route.snapshot.params['id'];

    //Get Team
    this.scrimService.getScrim(this.id).subscribe(scrim => {
        this.scrim = scrim;
    });

}

and here is the router-link i am using to get to this component

 <a *ngIf="recordOwner" [routerLink]="['/edit-scrim/'+id]" class="btn btn secondary">Edit</a>

I read in some answers to similar question like mine that I can use activatedRoute.params and subscribe to the data inside the constructor so that everything from ngOnInit method is called in the constructor, but I have no clue what that means and how to accomplish in my scenario :/

EDIT

id: string;
loggedInUser: string;

scrim: Scrim = {
name: '',
game: '',
time: '',
level: '',
description: '',
region: '',
platform: '',
acceptedBy: '',
acceptedDate: '',
acceptedStatus: '',
createdBy: '',
createdDate: '',
team: ''

}

teams: Team[];
myTeams: Team[] = [];
currentDate: string;
currentTime: string;

I have a service which gets "Teams" from a firebase database and returns an array of Model. I am using the currently logged in user's email address to find teams that were created by only the current user. Once i have those teams inside the array myTeams i am then trying to populate a select html tag with the team names from the myTeams list for the user to select. The first time i get to this edit-scrim page the teams in the select tag are populated just fine, but if i move to another page and comeback to this edit-scrim page using a RouterLink the select list is not populated because it doesn't call the ngoninit method again, so if i refresh my webpage the teams are populated again which i am guessing is because the ngoninit is called again.


Solution

  • You need to inject the activatedRoute into your constructor like this,

    constructor(private activatedRoute: ActivatedRoute) {
    this.activatedRoute.params.subscribe(
    params =>{
       this.id = params['id'];
       this.scrimService.getScrim(this.id).subscribe(scrim => {
            this.scrim = scrim;
        });
    
    }
    }