如何在angular4中为整个应用程序创建通用服务 [英] How to create a common service throughout the app in angular4

查看:54
本文介绍了如何在angular4中为整个应用程序创建通用服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在所有其他服务中都需要共同的服务.普通服务将仅启动一次.

I need a common service in all of the other services. The common service will be initiated one time only.

让我们说共同的服务是-

Lets say the common service is -

export Class CommonService
{
     _commonVar1= "";
     _commonVar2= "";
}

现在在所有其他服务中都需要公共服务的实例.请记住-commonservice将仅启动一次.

now the instance of common service is needed among all other services. Remember - the commonservice will be initiated one time only.

推荐答案

如果将服务放入提供者数组,则它们仅被实例化一次.他们基本上是单身.您可以像这样在应用模块中注册服务.

If you put service into providers array they are instantiated only once. They are basically singleton. You register services in app module like this.

providers: [ArticleService, Category1Service, Category2Service],

下一步,我们将在类声明的顶部使用@Injectable()装饰器,以使angular知道可以注入类.

In next step we will use @Injectable() decorator on top of class declaration to let angular know that class can be injected.

然后使用@Inject()将以下服务注入到另一个服务中,例如下面的示例.

And then inject following service to another service using @Inject() as in example bellow.

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

@Injectable()
export class ArticleService {
    public name: string;

    constructor() {
        this.name = "Awesome article";
    };
}

@Injectable()
export class Category1Service {
    constructor(@Inject(ArticleService) public articleService: ArticleService) { }
}

@Injectable()
export class Category2Service {
    constructor(@Inject(ArticleService) public articleService: ArticleService) { }
}

因为我们的Article服务已注册为单例,所以是正确的.

Because our Article service is registered as singleton following is true.

export class FooComponent {
    constructor(
        @Inject(ArticleService) private articleService: ArticleService,
        @Inject(Category1Service) private category1Service: Category1Service,
        @Inject(Category2Service) private category2Service: Category2Service,) {

        // both will print "Awesome article" 
        console.log(category1Service.articleService.name);
        console.log(category2Service.articleService.name);

        // change name in article service
        articleService.name = "Bad article";

        // both will print "Bad article"   
        console.log(category1Service.articleService.name);
        console.log(category2Service.articleService.name);    

    }
}

这篇关于如何在angular4中为整个应用程序创建通用服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆