I am encountering a problem when using a promise to retrieve a Degree object in Angular 2. The initial return statement (not commented out) in degree.service functions correctly when paired with the uncommented implementation of getDegree() in build.component. However, upon attempting to switch to either of the commented-out implementations utilizing a promise, the object consistently returns as "undefined"
degree.service.ts
import { Injectable } from '@angular/core';
import { Degree } from '../components/degree';
import { Category } from '../components/category';
import { Course } from '../components/course';
import { SAMPLE } from '../components/mock-degree';
@Injectable()
export class DegreeService{
getDegree(){
return SAMPLE;
// return Promise.resolve(SAMPLE);
// return new Promise<Degree>(function (resolve, reject) {
// resolve(SAMPLE);
// })
}
}
build.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { SEMANTIC_COMPONENTS, SEMANTIC_DIRECTIVES } from "ng-semantic";
import { Course } from '../course';
import { Category } from '../category';
import { PaneComponent } from './pane/pane.component';
import { Degree } from '../degree';
import { DegreeService } from '../../services/degree.service';
const blank: Category = {
name: '',
rank: 1,
rulestat: 'no',
categories: [],
courses: []
}
@Component({
selector: 'my-build',
directives: [SEMANTIC_COMPONENTS, SEMANTIC_DIRECTIVES, PaneComponent],
templateUrl: `app/components/build/build.component.html`,
providers: [DegreeService]
})
export class BuildComponent implements OnInit{
constructor(private degreeService: DegreeService){}
level: number = 1;
currDeg: Degree;
parents = [blank, blank, blank, blank];
setLast(lst: Category){ //pass category objects, do all UI changing here
this.level = lst.rank + 1;
this.parents[lst.rank - 1] = lst;
}
getDegree(){
//this.degreeService.getDegree().then(deg => this.currDeg = deg)
this.currDeg = this.degreeService.getDegree();
}
ngOnInit(){
this.getDegree();
}
}