我正在尝试在 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();
}
}