How to store token in Local or Session Storage in Angular 2?

前端 未结 9 2209
渐次进展
渐次进展 2020-11-27 12:27

I want to use Local or session storage to save authentication token in angular 2.0.0. I use angular2-localstorage

9条回答
  •  一整个雨季
    2020-11-27 13:13

    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) { }
     }
    

提交回复
热议问题