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

问题描述 投票:1回答:1

我正在努力重建我为新的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() { }

}

然后我创建一个看起来像这样的组件:

股份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],

我错过了什么吗?

javascript angular typescript angular5
1个回答
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访问服务中的所有公共函数和属性。

© www.soinside.com 2019 - 2024. All rights reserved.