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)
我不知道我做错了什么,但每次我导航到新页面并注入我的课程时,我都能看到正在创建一个新实例
如果您需要任何其他信息,请告诉我.
非常感谢这个问题的解决方案.
如果只需要一个实例,则不应多次提供该类.Angular DI为每个提供者维护一个实例.
因此除去ApplicationConfiguration从LogInComponent到
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})]);
| 归档时间: |
|
| 查看次数: |
1493 次 |
| 最近记录: |