Angular 2中的单个服务实例

Mih*_*hai 2 typescript angular2-services angular

首先,我知道这个答案之前已经发布了很多次,但我不能让我的工作成功,也许这里有人可以提供帮助.

我正在使用angular-cli beta 5来生成一个新项目.我使用角度2 rc1.

我有一个名为ApplicationConfiguration的类< - 这个我想创建一个实例,通过我的应用程序的每个组件.

在我的主要内容中,我有:

bootstrap(MyProjWebAppComponent, [ROUTER_PROVIDERS, HTTP_PROVIDERS, ApplicationConfiguration, provide(Http, {
  useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router, appConfig: ApplicationConfiguration) => new HttpServiceLayer(xhrBackend, requestOptions, router, appConfig),
  deps: [XHRBackend, RequestOptions, Router, ApplicationConfiguration]
})]);
Run Code Online (Sandbox Code Playgroud)

我的ApplicationConfiguration类:

@Injectable()
export class ApplicationConfiguration {

  constructor() {
    console.log('aaa');
  }
}
Run Code Online (Sandbox Code Playgroud)

以及我如何注入ApplicationConfiguration的示例组件:

import { ApplicationConfiguration } from '../..//services/application-configuration/application-configuration';
@Component({
  moduleId: module.id,
  selector: 'app-log-in',
  templateUrl: 'log-in.component.html',
  styleUrls: ['log-in.component.css'],
  directives: [ROUTER_DIRECTIVES],
  providers: [ApplicationConfiguration, LogInService]
})
export class LogInComponent implements OnInit {

 constructor(private _service: LogInService, private appConfig: ApplicationConfiguration, private _router: Router) { }
}
Run Code Online (Sandbox Code Playgroud)

我不知道我做错了什么,但每次我导航到新页面并注入我的课程时,我都能看到正在创建一个新实例

如果您需要任何其他信息,请告诉我.

非常感谢这个问题的解决方案.

Gün*_*uer 6

如果只需要一个实例,则不应多次提供该类.Angular DI为每个提供者维护一个实例.

因此除去ApplicationConfigurationLogInComponent

 providers: [LogInService]
Run Code Online (Sandbox Code Playgroud)

我不明白为什么你的定制需要工厂HttpServiceLayer.这应该做同样的事情:

更新(> = RC.5)

@NgModule({
  declarations: [MyProjWebAppComponent], 
  bootstrap: [MyProjWebAppComponent], 
  imports: [BrowserModule, RouterModule, HttpModule], 
  providers: [
   ApplicationConfiguration, 
   {provide Http: useClass: HttpServiceLayer})
  ]
});
Run Code Online (Sandbox Code Playgroud)

原始 自举(MyProjWebAppComponent,[ROUTER_PROVIDERS,HTTP_PROVIDERS,ApplicationConfiguration,提供(HTTP,{useClass:HttpServiceLayer})]);

  • 我不认为改变提供商在这方面有所帮助.该错误是由其他原因引起的.进口可能有问题.这个`'../..// services/...`看起来有点奇怪(`//`).你能再次检查一下吗? (2认同)