QuestionService に DataService を挿入しようとしていますが、「this.questions2」を割り当てると、AppComponent はまだ値が未定義であると考えています。私は得る
EXCEPTION: Error in ./AppComponent class AppComponent - inline template:3:20 caused by: Cannot read property 'forEach' of undefined
プランクはこちら
質問サービス
getQuestions(DataService: DataService<any>){
this.DataService.getData()
.subscribe(
function(response) {
this.questions2 = response;
return this.questions2;
},
function(error) { console.log("Error happened" + error)},
function() { console.log("the subscription is completed")}
);
}
データサービス
getData (){
return this.http.get(this.apiUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
console.log(body);
return body || { };
}
アプリコンポーネント
import { QuestionService } from './question.service';
@Component({
selector: 'my-app',
template: `
<div>
<h2>Job Application for Heroes</h2>
<dynamic-form [questions]="questions"></dynamic-form>
</div>
`,
providers: [QuestionService]
})
export class AppComponent {
questions: any[];
constructor(service: QuestionService) {
//why is the line below undefined?!
this.questions = service.getQuestions();
}
}