Angular 7 TypeError:service.x 不是函数

kee*_*tus 2 typescript angular

我制作了一个路由服务并想将它注入到我的导航组件中。但是当我调用它的方法时,它会抛出TypeError: routingService.getRequestedPage is not a function. 昨天我在另一个服务上遇到了一个非常相似的问题,不幸的是我忘记了我是如何解决这个问题的。我用终端生成了服务。

src/app/nav/nav.component.ts 构造函数:

constructor(private templateService: TemplateService, private routingService: RoutingService) {
    this.getTemplates();
    if (this.routingService.getRequestedPage() === 'home') {
      this.showHome();
    }
  }
Run Code Online (Sandbox Code Playgroud)

src/app/nav/nav.component.ts 进口:

import {RoutingService} from '../shared/routing.service';
Run Code Online (Sandbox Code Playgroud)

src/app/shared/routing.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class RoutingService {

  private requestedPage: string;

  constructor() {
    this.requestedPage = 'home';
  }

  requestPage(page: string) {
    this.requestedPage = page;
  }

  getRequestedPage() {
    return this.requestedPage;
  }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 7

而不是把providedIn 部分只是把@Injectable() 然后在你的app.module.ts 文件中添加服务提供者。然后当你写

constructor(private whateverService: WhateverService) {
}
Run Code Online (Sandbox Code Playgroud)
在任何组件中,您都应该可以无错误地访问。我看到您在代码段中将它设为私有,但那总是让我绊倒,因此在注入构造函数时确保它是私有的。

  • 这有效,你能解释一下为什么这个有效而另一个无效吗? (2认同)