These are chat archives for AngularClass/angular2-webpack-starter

19th
Nov 2015
Ben Radcliffe
@bradcliffe
Nov 19 2015 19:48
Does anyone have some example code for a simple service that's injectable to get a JSON file and parse it to an object that can be handed off to the root component in app.ts?
Basically I have a JSON file that I just want to retrieve and load into the app for seed data, but I'm not sure how to do this. I keep getting a lot of errors with my current implementation.
import {Injectable} from 'angular2/angular2';
import {Http} from 'angular2/http';

@Injectable()
export class DataService {

  constructor(http: Http) {
    this.http = http;
    this.data = null;
    console.log('DataService constructor');
  }

  retrieveData() {
    this.http.get('../data/user.json')
    .map(res => res.json())
    .subscribe(data => {
      this.data = data;
    });
  }
}
Ben Radcliffe
@bradcliffe
Nov 19 2015 19:53
I get Property 'http' does not exist on type 'DataService' and Property 'data' does not exist on type 'DataService', but this is modeled directly after articles I've read, and I'm not seeing them declare properties before the constructor function.
Carlos Liu
@carlosliu
Nov 19 2015 20:12
@bradcliffe You have to either declare the class member http and data, or use private or public in constructor parameters.
export class DataService {
  private http: Http;

  constructor(http: Http) { this.http = http; }
}
export class DataService {

  constructor(private http: Http) { }
}
It’s a “not-so-recent” typescript change. Please read http://www.typescriptlang.org/Handbook#classes-privatepublic-modifiers .
Ben Radcliffe
@bradcliffe
Nov 19 2015 20:20
Hmm.. Alright, @carlosliu, I just went with declaring members like you said. Actually did a bit of a rewrite.
import {Injectable} from 'angular2/angular2';
import {Http, Response} from 'angular2/http';

@Injectable()
export class AccountService {

  account: Object;
  http: Http;

  constructor(http: Http) {
    this.http = http;
    this.loadAccount();
  }

  loadAccount() {
    this.account = null;
    this.http.get('./api/goodstanding.json').map((res: Response) => res.json()).subscribe(res => this.account = res);
  }
}
Basically I want to instantiate the account across my app, so do I just need to inject this service into the root component's constructor?
Ben Radcliffe
@bradcliffe
Nov 19 2015 20:25
I think the loadAccount() method should actually be returning the account object? Is that right? So that I could inside my root component's constructor have something like:
constructor(public account: AccountService) {
    this.account = account.loadAccount();
  }
Ben Radcliffe
@bradcliffe
Nov 19 2015 20:50
Is that right? Am I instantiating the account for the app by returning the object from the AccountService? Or is this the wrong way to do things? It actually seems to be just returning an observable. I just want a plain object to read properties from to render into templates.