Angular 2 - Singleton服务导致其他服务的注入问题

时间:2018-06-12 09:10:31

标签: angular typescript singleton angular-services angular2-providers

我有很多代码,但我会尝试将其删除。我正在尝试将服务转换为单一服务(TagService)。但这似乎造成了问题。我有很多组件和服务,但我会简化为AddGroupComponent,TagComponent,TagService和ApiService。

要创建单例TagService,我将其添加到app.module.ts:

import {TagService} from './services/TagService';

const appRoutes: Routes = [
    ...
];

@NgModule({
    declarations: [
        TagComponent,
        ...
    ],
    imports: [
        ...
    ],
    entryComponents: [AddGroupComponent, ... ]
    providers: [TagService], // added this here
})

export class AppModule {
}

这是我的TagService,我在这里没有改变任何内容:

import {ApiService} from '../ApiService/ApiService';

@Injectable()
export class TagService {

    constructor(private api: ApiService) {
        ....
    }

这些是我想将TagService用作共享单例的一些组件。

// Didn't change anything here

@Component({
    ...
    providers: []
})
export class TagComponent {
    constructor(private api: ApiService, private tagService: TagService) {
        super();
    }

AddGroupComponent

@Component({
    ...
    providers: [ApiService, PermissionsService] // I removed TagService from here
})

export class AddGroupComponent {

    constructor(private api: ApiService, private tagService: TagService) {
        ...
    }

有了这个我得到错误:

AddGroupComponent_Host.ngfactory.js? [sm]:1 ERROR错误:StaticInjectorError(MgrModule)[TagsComponent - > ApiService]:   StaticInjectorError(Platform:core)[TagsComponent - > ApiService]:     NullInjectorError:没有ApiService的提供者!

我知道它没有提供者。在我看来,所有的TagComponents都已经将ApiService用作单例(它只创建了一次)。但我不确定发生了什么。

编辑:

我将ApiService添加到ngModule提供程序并将其从其他提供程序中删除。现在一切正常,但是我将console.logs添加到我的服务构造函数中,当我按下按钮创建AddGroupComponent时,仍然会创建一个新的ApiService和TagService(但是,当我多次按下它时,它们不会再次创建)。所以现在它创建它们两次(一次加载页面时,第二次点击打开AddGroupComponent的按钮。

编辑2:

没关系,我有另一个名为app.component.ts的文件,它有一个通用的MgrComponent,它也有这些服务作为提供者。好像现在一切正常。

0 个答案:

没有答案
相关问题