Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch in Angular2

Tags:

angular

What is the proper way to use fetch here? Right now my app is loading the JSON in the background (I can see it in Chrome's developer tools) but this.games is undefined after execution and I can't figure out why. I'm assuming I'm returning the data wrong.

Right now I have this in my app.ts

import {bootstrap, Component, View, CORE_DIRECTIVES, Pipe} from 'angular2/angular2';
import { Game } from './game/game';
import { API } from './services/API';
@Component({    
    selector: 'app',
    template: `
    {{games}}
            `,
    directives: [CORE_DIRECTIVES, Game]
})
export class App {
    games: any;
    constructor(api: API) { 
        api.fetchGames().then(function(json){
            this.games = json;
        });
    };


}
bootstrap(App, [API]);

and my API.ts:

declare var Zone, fetch, Request;
export class API {
    data: any;
    fetchGames() {
        return fetch('http://stats.nba.com/stats/scoreboardV2?DayOffset=0&LeagueID=00&gameDate=11%2F5%2F2015',{mode:'no-cors'})
            .then(function(response){
                return response.json();
            })
    }
}
like image 546
user5534715 Avatar asked Dec 30 '25 20:12

user5534715


1 Answers

I guess it is the same question as this one. The problem is in scope ('this') - 'this' inside promise callback is not the class. The simplest es6 solution is to change to es6 arrow function:

import {bootstrap, Component, CORE_DIRECTIVES, Pipe, Inject} from 'angular2/angular2';
  import { Game } from './game/game';
  import { API } from './services/API';
  import {NgZone} from 'angular2/angular2';

@Component({    
selector: 'app',
template: `
Hello
<button (click)="onClickMe()">Click me!</button>
<div *ng-for="#game of games" class = "game">
     //layout
</div>
`,
directives: [CORE_DIRECTIVES, Game],

 })
export class App {
data: any;
api: API;
games: Game[];

constructor(api:API) { 
    this.api = api;
    this.games = [];  
  api.fetchGames().then((response) => { //es6 arrow function will preserve class' 'this'
        this.data = response;
        console.log(this.data);
        var gamesTemp = [];
        this.teams = this.data.resultSets[1].rowSet;
        for (var i = 0; i < this.teams.length - 1; i += 2) {
            //manipulate            
        }
        this.games = gamesTemp;
        console.log(this.games);
    });
like image 107
Yaniv Efraim Avatar answered Jan 01 '26 12:01

Yaniv Efraim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!