我是ng2的新手,尝试使用Laravel作为我的后端,并使用ng2作为前端来设置auth系统。我设法在登录用户时获得令牌,但是我用localStorage存储它的代码只能工作一次并停止工作(在我刷新它后不会再设置)。localStorage不适用于Angular
auth.service.ts:
import { Injectable } from "@angular/core";
import { Http, Headers, Response } from "@angular/http";
import { Observable } from 'rxjs';
import 'rxjs/Rx';
@Injectable()
export class AuthService {
constructor(private http: Http){
}
signup(username: string, email: string, password: string){
return this.http.post('http://localhost:8000/api/user',
{name: username, email:email, password:password},
{headers: new Headers({'X-Requested-With': 'XMLHttpRequest'})});
}
signin(email: string, password: string) {
return this.http.post('http://localhost:8000/api/user/signin',
{email: email, password: password},
{headers: new Headers({'X-Requested-With': 'XMLHttpRequest'})})
.map(
(response: Response) => {
const token = response.json().token;
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-','+').replace('_','/');
return {token: token, decoded: JSON.parse(window.atob(base64))};
}
).do(
tokenData => {
localStorage.setItem('token', tokenData.token);
}
);
}
}
signin.component.ts:
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-signin',
templateUrl: './signin.component.html',
styleUrls: ['./signin.component.css']
})
export class SigninComponent implements OnInit {
constructor(private authService: AuthService) { }
ngOnInit() {
}
onSignin(form: NgForm){
this.authService.signin(form.value.email, form.value.password)
.subscribe(
tokenData => console.log(tokenData),
error => console.log(error)
);
}
}
signin.component.html:
<form (ngSubmit)="onSignin(f)" #f="ngForm">
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" ngModel class="form-control" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" ngModel class="form-control" required>
</div>
<button class="btn btn-primary" type="submit" [disabled]="!f.valid">Signin</button>
控制台中是否有任何错误? –
@Mr_Perfect nope,我从Laravel应用程序中正确获取令牌,但它不保存到localStorage。 – Tom