首页 > 解决方案 > 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可以解决问题,但它似乎不起作用。

标签: angularangular7angular-servicesangular-library

解决方案


推荐阅读