如何从 Angular 中的另一个服务调用一个服务的特定实例?
How to call a specific instance of a service from another service in Angular?
所以我有一个组件 "motions",它在通过一些用户输入单击按钮后执行 MotionService。然后,该服务需要将数据传递给 debateComponent 的特定 CaucusService 实例(我们称之为服务 A)或 DiscussComponent 的 CaucusService 实例 B,具体取决于输入。
但是,到目前为止,我似乎在 MotionService 中有一个 CaucusService 的新实例。
debateComponent 和 DiscussComponent 需要不同的 CaucusService 实例,所以我在每个 @Component
中都提供了它
基本上,在给定特定用户输入的情况下,我的 MotionService 需要将数据传递给 A 或 B
我该如何解决这个问题?
方法应该是这样的
在模块级别为要在组件之间共享的数据创建服务实例。
为仅包含组件日期的组件级使用创建单独的服务
即模块级别的 A 和 B 服务,用于在服务之间共享
A1 和 B1 组件级服务,其中包含组件特定数据。
import { Injectable, Injector } from '@angular/core';
import { FirstService } from './first.service';
@Injectable({
providedIn: 'root'
})
export class SecondService {
static firstService = new FirstService();
getFieldFromFirst() {
const field = SortingService.fileService.getField();
console.log(field);
}
}
这样试试
您可以通过两种方式指定服务的确切实例:
简单 - 使其成为单例服务
只需在服务声明中添加 providedIn: 'root'
语句即可确保该服务只有 1 个实例,这意味着您在任何地方使用它都将是同一个实例。
@Injectable({
providedIn: 'root'
})
export class CaucusService {}
困难 - 使用注入令牌
这有点复杂,但允许存在多个实例并在需要时引用。 angular 文档中提供了有关如何执行此操作的信息。
- https://angular.io/guide/dependency-injection-in-action
- https://angular.io/guide/dependency-injection-providers#non-class-dependencies
- https://angular.io/guide/dependency-injection#dependency-injection-tokens
一般建议
处理无状态服务比处理包含某种状态的服务要容易得多。因此,请尝试从组件中传递状态,这样您也可以更轻松地测试服务。
所以我有一个组件 "motions",它在通过一些用户输入单击按钮后执行 MotionService。然后,该服务需要将数据传递给 debateComponent 的特定 CaucusService 实例(我们称之为服务 A)或 DiscussComponent 的 CaucusService 实例 B,具体取决于输入。
但是,到目前为止,我似乎在 MotionService 中有一个 CaucusService 的新实例。
debateComponent 和 DiscussComponent 需要不同的 CaucusService 实例,所以我在每个 @Component
基本上,在给定特定用户输入的情况下,我的 MotionService 需要将数据传递给 A 或 B 我该如何解决这个问题?
方法应该是这样的 在模块级别为要在组件之间共享的数据创建服务实例。
为仅包含组件日期的组件级使用创建单独的服务
即模块级别的 A 和 B 服务,用于在服务之间共享 A1 和 B1 组件级服务,其中包含组件特定数据。
import { Injectable, Injector } from '@angular/core';
import { FirstService } from './first.service';
@Injectable({
providedIn: 'root'
})
export class SecondService {
static firstService = new FirstService();
getFieldFromFirst() {
const field = SortingService.fileService.getField();
console.log(field);
}
}
这样试试
您可以通过两种方式指定服务的确切实例:
简单 - 使其成为单例服务
只需在服务声明中添加 providedIn: 'root'
语句即可确保该服务只有 1 个实例,这意味着您在任何地方使用它都将是同一个实例。
@Injectable({
providedIn: 'root'
})
export class CaucusService {}
困难 - 使用注入令牌
这有点复杂,但允许存在多个实例并在需要时引用。 angular 文档中提供了有关如何执行此操作的信息。
- https://angular.io/guide/dependency-injection-in-action
- https://angular.io/guide/dependency-injection-providers#non-class-dependencies
- https://angular.io/guide/dependency-injection#dependency-injection-tokens
一般建议
处理无状态服务比处理包含某种状态的服务要容易得多。因此,请尝试从组件中传递状态,这样您也可以更轻松地测试服务。