I want to use Local or session storage to save authentication token in angular 2.0.0.
I use angular2-localstorage
import { Injectable,OpaqueToken } from '@angular/core';
export const localStorage = new OpaqueToken('localStorage');
Place these lines in the top of the file, it should resolve the issue.
Adding onto Bojan Kogoj's answer:
In your app.module.ts, add a new provider for storage.
@NgModule({
providers: [
{ provide: Storage, useValue: localStorage }
],
imports:[],
declarations:[]
})
And then you can use DI to get it wherever you need it.
@Injectable({
providedIn:'root'
})
export class StateService {
constructor(private storage: Storage) { }
}
Here is the best practice: https://github.com/PillowPillow/ng2-webstorage
I was use it in AngularJs, now with Angular2. Wery usefull.