【问题标题】:Unable to use Service as SingleTon object in Angular2 Final Release无法在 Angular2 最终版本中将服务用作 SingleTon 对象
【发布时间】:2016-10-05 12:05:30
【问题描述】:

我拥有并希望在整个应用程序中使用的服务是

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

@Injectable()
export class UserDetailsService {
    objUser: User = new User();
    testing: string;
    getData() {
        return this.testing;        
    }
    setData(my:string) {
        debugger;
        this.testing = my;
    }
}

现在我想在我的一个组件中设置变量 testing

import { Component } from '@angular/core';
import {UserDetailsService} from 'servicePath';

@Component({
    selector: 'some',
    templateUrl: 'someUrl',
    providers: [UserDetailsService]
})
export class LoginComponent {
constructor(private _Service: UserDetailsService)

}
onClick(){
_Service.set("my Value");
}

现在在另一个组件中,如果我想使用这个现场测试,我会得到未定义

import { Component } from '@angular/core';
import {UserDetailsService} from 'URL';

@Component({
    selector: 'somee1',
    templateUrl: 'url'
})
export class LandingComponent {
    constructor(private _UserService: UserDetailsService) {
        debugger;
        var test = _UserService.getData();
        debugger;
    }
}

在我的应用模块中我有这个

@NgModule({
    imports: ...,
    declarations:...,
    bootstrap: [AppComponent],
    providers: [HttpService, UserDetailsService]}]
})

【问题讨论】:

  • 我认为为了在多个组件中使用该服务,您需要一个共享模块。

标签: angular dependency-injection singleton angular2-services


【解决方案1】:

UserDetailsService从组件的providers中移除,只保留在@NgModule()的提供者中

Angular2 DI 为每个提供者维护一个实例。如果您多次提供它,您将获得多个实例。如果您在组件中提供它,您将获得应用程序中该组件的任何出现的实例。

添加到NgModule 的提供者都被添加到根作用域,如果多次提供服务,则只会将单个实例添加到根作用域。

延迟加载的模块拥有自己的作用域,因此这与之前解释的情况不同。

【讨论】:

  • 我正要提出同样的建议:(
  • 对不起:-/,不要气馁。
【解决方案2】:

创建共享模块:

创建共享模块:

@NgModule({
  imports: [CommonModule, RouterModule, ReactiveFormsModule ],
  declarations: [ ErrorMessagesComponent ],
  exports: [ CommonModule, ReactiveFormsModule, HttpModule, RouterModule, ]
})

export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [ AuthorizationService, LoginService, AuthGuardService ]
    };
  }
}

在 app.module.ts 中(注意 sharedModule.forRoot()):

@NgModule({
    imports: [ BrowserModule, RouterModule.forRoot(appRoutes), SharedModule.forRoot(), 
               HomeModule ],
    declarations: [ AppComponent ],
    bootstrap: [ AppComponent ],
    providers: [ appRoutingProviders ]

}) 

然后在每个使用共享模块的模块中:

@NgModule({
    imports: [ SharedModule, routing],
    declarations: [ HomeComponent], 
    bootstrap: [ HomeComponent ],
    providers: [ ]

}) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 2017-06-27
    • 2020-05-17
    • 2019-08-02
    • 2017-01-24
    相关资源
    最近更新 更多