如何跨多个组件共享通用功能

时间:2018-03-06 17:50:50

标签: javascript angular typescript angular5

我正在努力重建我为新的Angular 5框架构建的AngularJS应用程序。我承认我不会太熟悉打字稿和学习。

我正在尝试在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],

我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

为了使用该服务,您需要在组件中执行此操作:

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访问服务中的所有公共功能和属性。