我正在尝试在QuestionService中注入一个DataService,但是当我指定'this.questions2'时,AppComponent仍然认为该值未定义。我得到了
EXCEPTION: Error in ./AppComponent class AppComponent - inline template:3:20 caused by: Cannot read property 'forEach' of undefined
Plunkr here
QuestionService
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")}
);
}
的DataService
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 || { };
}
appcomponent
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();
}
}
答案 0 :(得分:1)
您没有正确使用observable。然后最终用户是应该订阅的用户。当您在问题服务中执行此操作时
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")}
);
}
函数中的返回不符合您的想法。这并不意味着你可以做到
questions = service.getQuestions();
这不是它的工作原理。它是应该订阅服务可观察的组件。所以,如果你考虑到这一点,问题服务是没用的。它没有目的。数据服务正在完成所有工作。因此,如果您仍想使用问题服务,那么您只需将呼叫返回getData
getQuestions() {
return this.dataService.getData();
}
就像我说的那样,它毫无用处。然后在您的组件中,您订阅服务
getQuestions().subscribe((data) => {
this.questions = data;
})
其他要提及的事项:
function
关键字。DataService
似乎仍然犯了同样的错误。questions
初始化为空数组。 questions = []
,因为可观察订阅是异步的,如果未初始化,模板将尝试使用未定义的值。