簡體   English   中英

Angular 2-即使已定義服務功能也未定義

[英]Angular 2 - Service function is undefined even though defined

我有一項服務可以發布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: {…} }

知道我在做什么錯嗎?

我認為問題出在調用您在組件中進行的訂閱。 在您提供的服務中,您將返回任何東西,請嘗試以下方法:

subscribeSubject(id): any {
  return this.http.post(environment.baseUrl + 'subscription', { subject: id, user_id: this.userService.currentUser._id })
          .map(res => {
            return this.loadUserSubscriptions().subscribe();
          });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM