Search code examples
functionangulartypescriptroutesangular2-routing

Angular2 : TypeError 'this.' is undefined


I wrote a function that gets and shows the "best player" from my array of objects (the player who has most likes). The function works fine and shows me what I want, but the browser shows me errors in the console, and the routing in my app is blocked (I can't navigate between components using routes)

this is my DashboardComponent Class

export class DashboardComponent implements OnInit {
  bestPlayer:Player;
  data:Player[]=[];
  max:number =0;
  constructor(private playerService : PlayerService ,private router: Router) { }

  ngOnInit() { 
    this.playerService.getData().then(data => {
      this.data = data;
      for (var i = 0; i <= this.data.length; i++) {
        if (this.data[i].likes>this.max) {
          this.max=this.data[i].likes;
          this.bestPlayer=this.data[i];
        }
      }
    });  
  }

  viewDetails(bestPlayer: Player):void {
    this.router.navigate(['/detail',this.bestPlayer.id]);
  }
}

This is my service:

import {Player} from './player';
import {PlayersData} from './muck-players';
import { Injectable } from '@angular/core';

@Injectable()
export class PlayerService {
  players:any;
  data:any;
  Player:Player;

  getData():Promise <Player[]> {
    return Promise.resolve(PlayersData);
  }
}

when I run the app the browser show me those errors :

TypeError: this.data[i] is undefined Error: Uncaught (in promise): Error: Cannot activate an already activated outlet Error: Uncaught (in promise): Error: Cannot activate an already activated outlet

when I delete whats in ngOninit() and viewDetails() function, routing starts working again and browser doesn't show me errors.

Any help please !


Solution

  • I have fixed dozens of errors in the Plunker and added some missing routing features. The App is working just fine now please take a look at my forked Plunker over here

    I fixed all the files paths and used in forEach method in your component just like this:

    ngOnInit() { 
      this.playerService.getData().then(data => {
          data.forEach( (arrData) => {
          if (arrData.likes>this.max) {
          this.max=arrData.likes;
          this.bestPlayer=arrData;
          }
        }) 
      });
    }
    

    Demonstration:

    enter image description here