Angular 2 - 如何将服务提供到应用程序模块级别

3

我在调用一个我认为已经被全局提供的服务内部函数时遇到了问题。我创建了一个名为SavedNotificationService的服务:

import { Injectable } from '@angular/core';

@Injectable()
export class SavedNotificationService {

    private showSavedNotification = false;

    show(): void {
        this.showSavedNotification = true;
    }

    hide(): void {
        this.showSavedNotification = false;
    }

}

我已经在app.module.ts文件中导入它:

import { SavedNotificationService } from "./saved-notification.service";
@NgModule({
providers: [SavedNotificationService]
})

但是当我想在服务中调用一个函数时,它会显示找不到该函数。虽然我已经在app.module中使服务可用,但我还需要在要使用服务的组件中导入它吗?(就像下面的示例一样)
@Component({
  providers: [SavedNotificationService]
})

1
你需要像这样导入它:import { SavedNotificationService } from "./saved-notification.service";。不应将其设置为提供程序。 - Suraj Rao
如果你将它添加到组件的提供者中,你将会得到一个不同于该组件(及其子组件)的实例。如果你不想要这样做,就不要将它添加到提供者中。 - Günter Zöchbauer
@suraj 我必须在我想要使用它的实际组件上执行吗? - Andrew Howard
2个回答

4

您需要将其导入,然后通过构造函数将其作为依赖项注入到组件中。

像这样:

import { ExampleService } from '....' // where your services are.

@Component({
    moduleId: module.id,
    selector: 'example-component',
    templateUrl: 'example-component.html'
})
export class ExampleComponent implements OnInit {
    constructor(private _exampleService: ExampleService) { 
    }

这里可以阅读有关注入服务及其使用的更多信息。

P.S:如果您在全局范围(AppModule)注册您的服务,您将能够在应用程序的任何地方进行注入。您还可以在给定的模块中注册您的服务,其中注入的范围将不同。(您应该小心处理,因为在给定时间可能会出现不同实例的服务。)


哦,我以为在 app.module 级别导入服务的好处是可以避免在每个需要使用它的组件上都进行导入。那么无论如何,您总是需要在每个单独的组件上进行导入吗? - Andrew Howard
1
@AndrewJuniorHoward,不行。您必须导入该服务并在想要使用它的任何地方注入它。通过将提供程序放入AppModule中,您基本上是在说您可以在应用程序中的任何地方注入它(每个组件都是如此)。 - Kerim Emurla
啊,好的,如果你把它放到 app.module 的 providers 中,那么你就不必在组件级别声明提供者了,但你仍然需要进行导入操作? - Andrew Howard
1
@AndrewJuniorHoward,没错。导入 + 构造函数注入。正如我在我的回答中所说,您可以有不同范围的服务,在您的情况下最好将它们放在 AppModule 的 providers 数组中。在这样做之后,您可以在任何组件的构造函数中注入服务并访问它。 - Kerim Emurla

2
在模块中声明服务后,无需在组件中重新声明...只需在组件中导入并在构造函数中初始化即可,如下所示:
import { SavedNotificationService } from "./saved-notification.service";
@Component({
})
export class xyz{

service;

constructor(service:SavedNotificationService)
{

}
//call the method using this instance
service.show();

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接