I am trying to store token in local storage for Auth using the AngularJS ngStorage module. I want to know that how to store in local storage .
I using a laravel powered angular stack on github: https://github.com/jadjoubran/laravel5-angular-material-starter
I have the following code:
create_login_form.component.js
class CreateLoginFormController{
constructor(API,ToastService){
'ngInject';
this.API = API;
this.ToastService = ToastService;
}
submit(){
var data = {
email: this.email,
password: this.password
};
this.API.all('users/login').post(data).then((response) => {
this.ToastService.show(response.data.token);
<--- $localStorage -->
});
}
}
export const CreateLoginFormComponent = {
templateUrl: './views/app/components/create_login_form/create_login_form.component.html',
controller: CreateLoginFormController,
controllerAs: 'vm',
bindings: {}
}
create_login_form.component.html
<form ng-submit="vm.submit()">
<md-input-container>
<label>Email</label>
<input type="text" ng-model="vm.email">
</md-input-container>
<md-input-container>
<label>Password</label>
<input type="password" ng-model="vm.password">
</md-input-container>
<md-button type="submit" class="md-primary md-raised">Login</md-button>
</form>
API.service.js
export class APIService {
constructor(Restangular, ToastService, $localStorage) {
'ngInject';
//content negotiation
var headers = {
'Content-Type': 'application/json',
'Accept': 'application/x.laravel.v1+json'
};
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer
.setBaseUrl('/api/')
.setDefaultHeaders(headers)
.setErrorInterceptor(function(response) {
if (response.status === 422) {
for (var error in response.data.errors) {
return ToastService.error(response.data.errors[error][0]);
}
}
})
.addFullRequestInterceptor(function(element, operation, what, url, headers) {
if ($localStorage.jwt) {
headers.Authorization = 'Bearer ' + $localStorage.jwt;
}
});
});
}
}
RoutesConfig.js
export function RoutesConfig($stateProvider, $urlRouterProvider) {
'ngInject';
var getView = function(viewName) {
return './views/app/pages/' + viewName + '/' + viewName + '.page.html';
};
$urlRouterProvider.otherwise('/');
$stateProvider
.state('app', {
abstract: true,
views: {
header: {
templateUrl: getView('header')
},
footer: {
templateUrl: getView('footer')
},
main: {}
}
})
.state('app.landing', {
url: '/',
data: {},
views: {
'main@': {
templateUrl: getView('landing')
}
}
})
.state('app.login',{
url: '/create_login',
views: {
'main@': {
templateUrl :getView ('create_login')
}
}
})
.state('app.create_post', {
url: '/create-post',
views: {
'main@': {
templateUrl: getView('create_post')
}
}
});
}