【问题标题】:How to share common functions across multiple components如何跨多个组件共享通用功能
【发布时间】:2018-03-06 17:50:49
【问题描述】:

我正在重建一个我为新的 Angular 5 框架构建的 AngularJS 应用程序。我承认我对 Typescript 和边走边学不太熟悉。

我正在尝试在 AngularJS 中重新创建一个等效的服务。我有许多需要通过多个组件访问的常用功能。因此,通过 Angular CLI,我使用了以下命令:ng generate service Common。然后我添加了一个测试函数并尝试将服务注入我的组件并尝试调用它。我收到一条错误消息,提示找不到名称 ServiceTest。

Common.service.ts

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

@Injectable()
export class CommonService {

  public ServiceTest(data) {
    console.log(data)
  }

  constructor() { }

}

然后我创建一个如下所示的组件:

Share-Buttons.Components.ts

import { Component, OnInit } from '@angular/core';
import { CommonService } from '../../common.service';


@Component({
  selector: 'app-shared-buttons',
  templateUrl: './shared-buttons.component.html',
  styleUrls: ['./shared-buttons.component.css']
})
export class SharedButtonsComponent implements OnInit {

  public params: any;

  agInit(params: any): void {
    this.params = params;
  }

  public invokeServiceTest() {
    ServiceTest(this.params.data);
  }

  constructor() { }

  ngOnInit() {
  }

在我的 aoo.modules 中,服务位于我的提供程序中,如下所示:

  providers: [CommonService],

我错过了什么吗?

【问题讨论】:

  • 问题是你没有通过构造函数将服务注入到组件中。
  • constructor(private commonService: CommonService) { this.commonService.ServiceTest("something")}

标签: javascript angular typescript angular5


【解决方案1】:

这是您需要在组件中执行的操作才能使用服务:

import { Component, OnInit } from '@angular/core';
import { CommonService } from '../../common.service';


@Component({
  selector: 'app-shared-buttons',
  templateUrl: './shared-buttons.component.html',
  styleUrls: ['./shared-buttons.component.css']
})
export class SharedButtonsComponent implements OnInit {

  public params: any;

  agInit(params: any): void {
    this.params = params;
  }

  public invokeServiceTest() {
    this.commonService.ServiceTest(this.params.data);
  }

  constructor(private commonService: CommonService) { }

  ngOnInit() { }
}

如您所见,服务是通过构造函数注入的。然后,在invokeServiceTest 中调用服务函数。

使用带有private(或public)关键字的构造函数注入服务会为服务创建一个局部变量。在这种情况下,您可以通过this.serviceNamethis.commonService 访问服务中的所有公共函数和属性。

【讨论】:

  • 它似乎工作,但我得到奇怪的错误ERROR Error: StaticInjectorError(AppModule)[SharedButtonsComponent -> CommonService]: StaticInjectorError(Platform: core)[SharedButtonsComponent -> CommonService]: NullInjectorError: No provider for CommonService! 这对你意味着什么吗?
  • 通常,这意味着您缺少在 app.module.ts 的 providers 数组中列出的 CommonService。但是,根据你的帖子,你有。您是否出于某种原因将其删除?
  • 您的SharedButtonsComponent 包含在哪里?
  • 通过更新我的 Angular CLI 版本并运行 ng serve --preserve-symlinks 来修复它。不太清楚发生了什么,但现在似乎还好。
猜你喜欢
  • 2018-08-23
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
  • 2018-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多