angular - Angular 服务不是那么单一
问题描述
我正在开发一个 Angular7 应用程序。在我的项目中,我有几个库,其中一些包含服务。
假设我在一个名为NotificatorService
的库中调用了一项服务lib-controls
import { Notifications } from './notifications.enum';
import { INotificationService } from './notification-service.interface';
@Injectable({
providedIn: 'root'
})
//service in charge of notification handling
export class NotificatorService implements INotificationService {
//notifications array
notifications: Array<any> = new Array<any>();
constructor() {
console.log('init');
}
//when a notifaction is displayed
notify(keyword: Notifications) {
console.log(keyword);
this.notifications.push(keyword);
}
}
仍然在我的lib-controls
库中,我有几个控件可以注入此服务,例如:
import { Notifications } from '../../../../notifications/notifications.enum';
import { NotificatorService } from '../../../../notifications/notificator.service';
@Component({
selector: 'send-mail',
templateUrl: './send-mail.component.html',
styleUrls: ['./send-mail.component.css']
})
export class SendMailComponent {
constructor(private _notificationService: NotificatorService) {
}
notifyMailState(keyword: Notification) {
this._notificationService.notify(keyword);
}
}
现在从我的应用程序组件中,我还想注入此服务以发送通知
import { NotificatorService } from 'lib-controls';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [{ provide: SendMailAbstract, useClass: SendmailService }, {
provide: SendUsbAbstract, useClass: SendUsbService }]
})
export class AppComponent implements AfterViewInit {
constructor(
private _notificatorService: NotificatorService) {
}
notify() {
this._notificatorService.notify(<Notifications>('OFFLINE'));
}
}
请注意,导入现在不是相对路径,而是直接针对库。
从这里我可以看到,服务似乎被实例化了两次。一个用于来自 的所有注入lib-controls
,一个用于应用程序本身。
在这里,我们可以看到,对于同一个服务,我们也有两条不同的路径。
这导致了这样一个事实,即我的notifications
数组不包含我的所有通知,而是包含每个服务实例中的每个应用程序的通知和lib-controls
另一方面每个库的通知。
无论服务如何导入(相对或从库),我都希望整个应用程序只有一个服务实例
我试图在我的模块中玩,providers
但没有任何改变。虽然我认为这providedIn: root
可以解决问题,但它似乎不起作用。
解决方案
推荐阅读
- python - Python:write() 函数可以处理的值是否有最大值?
- c++ - 如何在 for 循环中编写此表?
- java - 使用 vscode 远程调试 java 云应用
- python - 无法嗅探以太网类型 0x0102 自定义数据包
- php - 警告:mysql_fetch_array() 期望参数 1 是资源... - 为什么?
- c - 不使用 strlen() 函数计算字符串的长度
- c++ - 在取消引用向量时遇到问题
- indexing - 当一行被删除时,它不是物理删除,而是标记为已删除。太极数据
- vue.js - 在 Vue.js 中从 index.html 调用组件
- angular - Firebase 电子邮件验证电子邮件问题