Reputation: 18719
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.
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:
ORIGINAL EXCEPTION: TypeError: Cannot read property 'post' of undefined ORIGINAL STACKTRACE:
Upvotes: 0
Views: 82
Reputation: 55443
singleton pattern can be achieved through sharedService
. You have to inject it into bootstrap
function like
bootstrap(AppComponent,[sharedService]); //
I have read your updated question. Plunker which shares object like you want.
Upvotes: 3
Reputation: 657871
Add the service to the providers list in
bootstrap(AppComponent, [OtherProviders, MySingletonService]);
(don't add MySingletonService
anywhere else to providers
.
Angular2 DI ensures that the same instance is injected everywhere.
Upvotes: 1