From this repo, I've successfully configured this:
import {Component} from "angular2/core";
import {LocalStorageService} from "angular2-localstorage/LocalStorageEmitter";
@Component({
provider: [LocalStorageService]
})
export class AppRoot{
constructor(private storageService: LocalStorageService){}
...
}
How can I use storageService to set or get in local storage? I can't find example anywhere even in the doc.
After some testing, I've managed it to get it working with Decorator through WebStorage:
import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";
@Component({})
export class LoginComponent implements OnInit {
@LocalStorage() public username:string = 'hello world';
ngOnInit() {
console.log('username', this.username);
// it prints username hello world
}
}
However, when I used Chrome Dev to see my localstorage, I see nothing there:
And In another component,
import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";
@Component({})
export class DashboardComponent implements OnInit {
@LocalStorage() public username:string;
ngOnInit() {
console.log(this.username);
// it prints null
}
}
The service is imported into the app only so that it can run initialisation code.
The way you are supposed to use this is via decorators as other answers mentioned.
Note that this means you only need to import the service into your root most (app) component only, not all the components that use the decorators.
Update
Also try using the first way in Step 2 of the instructions, using bootstrap
instead of AppComponent
.
Unfortunately this library is looking for a new maintainer. so not sure how reliable it is.