Angular 2令牌和身份验证

时间:2016-11-28 09:28:19

标签: angular

我会在角度2中创建一个身份验证。我创建了一个帖子服务:

constructor(http: Http) {
    this.http = http;
    let currentUser: IUserTokenType = JSON.parse(localStorage.getItem("currentUser"));
    this.token = currentUser && currentUser.token;
}
public loginC (username: string, password: string): Observable<boolean> {
     return this.http.post( authURL + loginURL,
                             JSON.stringify({  password, username }))
     .map((response: Response) => { 
         let token: string = response.json() && response.json().token;
         if (token) {
             this.token = token;
             localStorage.setItem("currentUser", JSON.stringify({ token, username}));
             return true;
         } else {
             return false;
         }
     });
 }

login()函数:

private router: Router;
private authenticationService: ServerDataComponent;
constructor (router: Router, authenticationService: ServerDataComponent) {
    this.router = router;
    this.authenticationService = authenticationService;
}
public login(): void {
    this.loading = true;
    this.authenticationService.loginC(this.model.username, this.model.password)
        .subscribe((result: boolean) => {
            if (result === true) {
                this.router.navigate(["table_per"]);
            } else {
                this.error = "Введен неверный логин и/или пароль";
                this.loading = false;
            }
        });
}

这是我的模板:

<form name="form" class="form col-md-12 center-block">
      <div class="form-group">
        <input type="text" class="form-control input-lg" [(ngModel)]="model.username" placeholder="Логин" name="username">
      </div>
      <div class="form-group">
        <input type="password" class="form-control input-lg" [(ngModel)]="model.password" placeholder="Пароль" name="password">
      </div>
      <div class="form-group">
        <button (click)="login()" class="btn btn-primary btn-lg btn-block" type="submit">Войти</button>
      </div>
      <div *ngIf="error" class="alert alert-danger">
        {{error}}
      </div>
    </form>

当我点击按钮登录时,我有这个错误:Unexpected of json input。也许角度没有读取令牌?

1 个答案:

答案 0 :(得分:1)

您必须为JSON属性声明名称。

有两个有问题的JSON对象!

JSON.stringify({ 'password': password, 'username': username })
JSON.stringify({ 'token': token, 'username': username})
public loginC (username: string, password: string): Observable<boolean> {
   return this.http.post( authURL + loginURL, JSON.stringify({
         'password': password,
         'username': username
      }))
     .map((response: Response) => { 
         let token: string = response.json() && response.json().token;
         if (token) {
             this.token = token;
             localStorage.setItem("currentUser", JSON.stringify({ 'token': token, 'username': username}));
             return true;
         } else {
             return false;
         }
     });
 }