I'm wrestling with an undefined return from a promise. From my detective work, it seems that the problem is assigning the results from the promise to a instance variable on the component where I am calling the promise. I think it is a type(or similar) problem with the arrow function where I try to assign the returned survey to this.survey.
Any insight would be appreciated!
./survey.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { SURVEYS } from './mock-survey';
export class Option {
constructor(public id: number,
public text: string,
public value: number
){}
}
export class Question {
constructor(public id: number,
public type: string,
public text: string,
public required: boolean,
public options: Option[] = []
){}
}
export class Survey {
constructor(public id: number,
public name: string,
public description: string,
public instructions: string,
public questions: Question[] = []
){}
}
@Injectable()
export class SurveyService {
getSurveys(): Promise<Survey[]> {
return Promise.resolve(SURVEYS);
}
getSurvey(id: number | string): Promise<Survey> {
return this.getSurveys()
.then(surveys => surveys
.find(survey => survey.id === +id));
}
public observable: Observable<any>;
}
./survey.component.ts
import 'rxjs/add/operator/switchMap';
import { Observable } from 'rxjs/Observable';
import { Component, OnInit, Inject, HostBinding } from '@angular/core';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { Survey, SurveyService } from '../survey.service';
@Component({
selector: 'app-survey',
templateUrl: './survey.component.html',
styleUrls: ['./survey.component.scss'],
providers: [SurveyService]
})
export class SurveyComponent implements OnInit {
survey: Survey
surveyResults: {}
constructor(
private surveyService: SurveyService,
public dialogRef: MdDialogRef<SurveyComponent>,
@Inject(MD_DIALOG_DATA) public data: any
) { }
// getSurveys(): void {
// this.surveyService.getSurveys().then(
// surveys => this.surveys= surveys);
// }
// *This method also returns an undefined this.survey; Not issue with ngOnInit()
// getSurvey(): void {
// let survey_id = this.data.survey_id
// this.surveyService
// .getSurvey(survey_id)
// .then(s => {this.survey = s});
// }
ngOnInit(): void {
this.surveyService
.getSurvey(this.data.survey_id)
.then((survey: Survey) => {this.survey = survey});
// returns survey_id from MD_DIALOG_DATA
console.log(this.data.survey_id)
// returns survey JSON object; This arrives in browser console
console.log(this.surveyService.getSurvey(this.data.survey_id));
// returns undefined
console.log(this.survey);
}
confirmSurveyResults() {
this.dialogRef.close(this.surveyResults);
console.log(this.survey);
}
}