[英]How to create singleton Object like a Angular1 Service?
I am wondering how can I create singleton object in Angular2, that will hold the value of some attributes throughout life of application - so that I can use it in many components, and inject it. 我想知道如何在Angular2中创建单例对象,该对象将在应用程序的整个生命周期中保持某些属性的值-以便可以在许多组件中使用它并注入它。
Any ideas? 有任何想法吗?
Thanks 谢谢
My attempt was to do: 我的尝试是:
bootstrap(MyApp,[ROUTER_PROVIDERS,
HTTP_PROVIDERS,
provide(LocationStrategy, {useClass: HashLocationStrategy}),
provide(APP_BASE_HREF, {useValue: '/'}),Login])
where
Login:
@Injectable()
export class Login {
public username: string = "any";
constructor(private _http:Http, private _router:Router){
}
public static login(username,password){
var creds = 'username=' + username+'&password='+password;
this._http.post('/authentication/login',creds,{headers: contentHeaders})
.subscribe(
success =>{
this.username = success.json().username;
this._router.navigate(['Dashboard']);
},
error =>{
console.log('Wrong creds')
});
}
public getUsername(){
return this.username;
}
}
In this case, getUsername() works, but this._http post does not - it throws an error: 在这种情况下,getUsername()有效,但是this._http帖子不起作用-它引发错误:
ORIGINAL EXCEPTION: TypeError: Cannot read property 'post' of undefined ORIGINAL STACKTRACE: 原始异常:TypeError:无法读取未定义原始堆栈的属性“ post”:
singleton pattern can be achieved through sharedService
. 单例模式可以通过sharedService
实现。 You have to inject it into bootstrap
function like 您必须将其注入bootstrap
功能,例如
bootstrap(AppComponent,[sharedService]); //
I have read your updated question. 我已经阅读了您更新的问题。 Plunker which shares object like you want. 随心所欲共享对象的柱塞 。
Add the service to the providers list in 将服务添加到以下位置的提供者列表中
bootstrap(AppComponent, [OtherProviders, MySingletonService]);
(don't add MySingletonService
anywhere else to providers
. (不要将MySingletonService
添加到providers
其他任何位置。
Angular2 DI ensures that the same instance is injected everywhere. Angular2 DI确保将相同的实例注入到各处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.