[英]How to share common functions across multiple components
我正在努力重建为新的Angular 5框架构建的AngularJS应用程序。 我承认我不太喜欢Typescript和学习。
我试图在AngularJS中重新创建服务的对等物。 我有许多常用功能,需要我通过多个组件进行访问。 因此,通过Angular CLI,我使用了以下命令: ng generate service Common
。 然后,我添加了一个testfunction,并尝试将服务注入到我的组件中并尝试调用它。 我收到一条错误消息,说它找不到名称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],
我想念什么吗?
这是您需要在组件中执行的操作,以使用服务:
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.serviceName
和this.commonService
访问服务中的所有公共功能和属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.