【发布时间】:2017-07-31 04:32:08
【问题描述】:
我正在努力解决一个未定义的承诺回报。从我的侦探工作来看,问题似乎是将承诺的结果分配给我调用承诺的组件上的实例变量。我认为这是箭头函数的类型(或类似)问题,我尝试将返回的调查分配给 this.survey。
任何见解将不胜感激!
./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);
}
}
【问题讨论】:
-
能否提供
mock-survey文件的内容? -
感谢您的快速回复。我现在明白为什么它会在 ngOnInit 函数中返回 undefined。
标签: angular typescript promise angular-services arrow-functions