bill-lamin
bill-lamin

Reputation: 343

Angular 2, Getting Data Out of Service

I'm currently trying out Angular 2 and am having trouble seeing the data returned from the service I created. In developer tools I see the getSubjects() api call firing, but I never see any data shown in the view. Any ideas? Am I missing something obvious?

SubjectService.ts

import {Injectable} from "angular2/core";
import {Http, Response, HTTP_PROVIDERS} from "angular2/http";

@Injectable()
export class SubjectService{
    constructor(public http: Http){

    }

   getSubject(){
       return this.http.request('/subjects.json')
         .map(response => response.json())
            .subscribe(
                res => this.subjects = res,
                err => this.logError(err)
            );
    }
}

DashboardComponent.ts

import { Component, View } from 'angular2/core'
import { CORE_DIRECTIVES } from "angular2/common"
import {SubjectService} from "../../services/subject/SubjectService.ts"
import 'rxjs/add/operator/map';

@Component({
    selector: 'dashboard',
    providers: [SubjectService]
})

@View({
    template: `
      <div class="row">
        <div class="medium-12 columns">
            <h1>Dashboard!</h1>
            {{subjects}}
        </div>
      </div>
    `
})

export class DashboardComponent{

    constructor(subjectService: SubjectService){
     subjectService.getSubject()
    }
}

Upvotes: 1

Views: 189

Answers (1)

sdfacre
sdfacre

Reputation: 1273

move

.subscribe(
            res => this.subjects = res,
            err => this.logError(err)
        )

from service to component should work

constructor(subjectService: SubjectService){
 subjectService.getSubject().subscribe(
            res => this.subjects = res,
            err => this.logError(err)
        );
}

Upvotes: 3

Related Questions