我是ng2的新手,并尝试使用Laravel作为我的后端并使用ng2作为前端来设置auth系统。我设法在用户登录后获得一个令牌,但我写的用localStorage存储它的代码只工作一次并停止工作(刷新后它已经消失,不会再次设置)。
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>
答案 0 :(得分:0)
我有一个类似的应用程序,但我只是使用localStorage如下:
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('_','/');
localStorage.setItem('token', token);
return {token: token, decoded: JSON.parse(window.atob(base64))};
}
);
}
所以显然do(){}部分永远不会被调用。