加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

另一个服务中的Angular2 Inject服务创建了2个实例

发布时间:2020-12-17 07:01:25 所属栏目:安全 来源:网络整理
导读:我有两个服务:AuthService和MonBanquetService,AuthService依赖于MyService.以下是这两项服务的基本代码: AuthService.ts: import {Inject,Injectable} from 'angular2/core';import {MonBanquetService} from '../monbanquet.service'@Injectable()expor
我有两个服务:AuthService和MonBanquetService,AuthService依赖于MyService.以下是这两项服务的基本代码:

AuthService.ts:

import {Inject,Injectable} from 'angular2/core';
import {MonBanquetService} from '../monbanquet.service'

@Injectable()
export class AuthService {

    public username: string;

    constructor(protected _monBanquetService: MonBanquetService) {
        // do something()
    }

}

MonBanquetService.ts

import {Injectable,Component} from 'angular2/core';
import {Http,Headers,Response} from 'angular2/http';
import {Router} from 'angular2/router';

@Injectable()
export class MonBanquetService {

    constructor(public http: Http,private _router: Router) {
        console.log('MonBanquetServices created');
    }
}

我把这两个服务作为提供者放在boot.ts中:

bootstrap(AppComponent,[
    ROUTER_PROVIDERS,provide(LocationStrategy,{useClass: HashLocationStrategy}),HTTP_PROVIDERS,MonBanquetService,AuthService
]);

但是,当我运行应用程序时,我看到两个控制台日志’MonBanquetServices created’.
我认为服务应该是单身,怎么会有两个实例呢?

谢谢.

解决方法

Angular为每个提供程序维护一个实例.如果在多个位置添加类型作为提供程序,则会导致多个实例.

当从DI请求密钥(类型,令牌)时,它会查找层次结构并从找到的第一个提供程序返回实例.

因此,如果您想要一个全局实例,只需将其添加到提供者列表中

bootstrap(AppComponent,[MonBanquetService])
@NgModule(
  providers: [MonBanquetService],....
)
export class AppMpdule{}

或者根据Angular团队的建议,将自定义提供程序提供给根组件的提供程序列表

@Component({
  selector: 'my-app',providers: [MonBanquetService]
})
class AppComponent {
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读