Angular 7 TypeError:service.x不是函数 [英] Angular 7 TypeError: service.x is not a function

查看:65
本文介绍了Angular 7 TypeError:service.x不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提供了路由服务,并希望将其注入到我的导航组件中.但是,当我在其上调用方法时,它会引发 TypeError:routingService.getRequestedPage不是函数.昨天,我在另一项服务中遇到了非常相似的问题,但不幸的是,我忘记了如何解决此问题.我通过终端生成了服务.

I made a routing service and want to inject it into my nav component. But when i call a method on it it throws TypeError: routingService.getRequestedPage is not a function. Yesterday I had a very similar problem with another service, unfortunately I forgot how I solved this. I generated the service it with the terminal.

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

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

src/app/nav/nav.component.ts 导入:

import {RoutingService} from '../shared/routing.service';

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;
  }
}

推荐答案

而不是将providerIn部分放到@Injectable()中,然后在您的app.module.ts文件中将服务添加到提供者下.然后,当您编写

Instead of putting the providedIn part just put @Injectable() then in your app.module.ts file add the service under providers. Then when you write

constructor(private whateverService: WhateverService) {
}

在任何组件中,您都应该可以正常访问.我看到您在代码段中将其设置为私有,但是多数民众赞成在其中,这总是让我绊倒,因此请确保在将其注入构造函数时将其私有.

In any component you should have access without errors. I see you have it as private in the snippet but thats one that always trips me up so make sure its private when injecting into the constructor.

这篇关于Angular 7 TypeError:service.x不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆