我有一个发布http请求的服务。我尝试从组件添加服务,我不断收到未定义的错误。我可以肯定地看到它被定义以及按住Ctrl键点击它会带我到正确的功能。我仔细检查的另一件事是在模块中注入服务,这也是完成的。这是我的代码:
HTML:
<i (click)="subscribeSubject(subject._id)" class="fa fa-cart-plus fa-2x"></i>
TS:
subscribeSubject(id) {
this.subscriptionService.subscribeSubject(id).subscribe();
}
服务:
subscribeSubject(id): any {
this.http.post(environment.baseUrl + 'subscription', { subject: id, user_id: this.userService.currentUser._id })
.map(res => {
this.loadUserSubscriptions().subscribe();
});
}
以下是我在控制台中收到的错误:
ERROR
TypeError: this.subscriptionService.subscribeSubject(...) is undefined
Stack trace:
CoursesComponent.prototype.subscribeSubject@webpack-internal:///../../../../../src/app/component/courses/courses.component.ts:33:9
View_CoursesComponent_4/<@ng:///AppModule/CoursesComponent.ngfactory.js:12:23
handleEvent@webpack-internal:///../../../core/esm5/core.js:13778:115
callWithDebugContext@webpack-internal:///../../../core/esm5/core.js:15287:39
debugHandleEvent@webpack-internal:///../../../core/esm5/core.js:14874:12
dispatchEvent@webpack-internal:///../../../core/esm5/core.js:10187:16
renderEventHandlerClosure/<@webpack-internal:///../../../core/esm5/core.js:10808:38
decoratePreventDefault/<@webpack-internal:///../../../platform-browser/esm5/platform-browser.js:2680:53
ZoneDelegate.prototype.invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:425:17
onInvokeTask@webpack-internal:///../../../core/esm5/core.js:4941:24
ZoneDelegate.prototype.invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:424:17
Zone.prototype.runTask@webpack-internal:///../../../../zone.js/dist/zone.js:192:28
ZoneTask.invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:499:24
invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:1540:9
globalZoneAwareCallback@webpack-internal:///../../../../zone.js/dist/zone.js:1566:17
CoursesComponent.html:24:16
ERROR CONTEXT
Object { view: {…}, nodeIndex: 0, nodeDef: {…}, elDef: {…}, elView: {…} }
知道我做错了吗?
答案 0 :(得分:2)
我认为问题在于您在组件中调用订阅。在您的服务中,您将返回任何内容,尝试使用此方法:
subscribeSubject(id): any {
return this.http.post(environment.baseUrl + 'subscription', { subject: id, user_id: this.userService.currentUser._id })
.map(res => {
return this.loadUserSubscriptions().subscribe();
});
}