2017-03-21 100 views
1

我有一个服务来验证我的用户,但我不知道为什么它不会进入subscribe方法,即使我把正确的凭据。Angular2:订阅方法不起作用

当我把正确证书拿给invalid user这意味着 是isAuthentifiated仍然false

服务

import { Injectable } from '@angular/core'; 

import { Http, Response, Headers } from '@angular/http'; 
import { Observable } from 'rxjs/Rx'; 

import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 

@Injectable() 
export class LoginService { 
isAuthenticated: boolean = false; 

    constructor(private http: Http) { 

    } 

    login(username: string, password: string) { 
    const headers = new Headers(); 
    const creds = 'username=' + username + '&password=' + password; 

    headers.append('Authorization', 'Basic ' + btoa(username + ':' + password)); 
    headers.append('Content-Type', 'application/x-www-form-urlencoded'); 

    return new Promise((resolve) => { 
     this.http.post('http://localhost:8080/StudentManager/login', creds, { headers: headers }) 
     .map(this.extractData) 
     .subscribe(
      data => { 
        if(data.success) { 
       window.localStorage.setItem('auth_key', data.token); 
       console.log('hi'); 
       this.isAuthenticated = true; 
        } 
       resolve(this.isAuthenticated); 
      }); 

    } 
    ); 
    } 
    private extractData(res: Response) { 
    let body; 

    // check if empty, before call json 
    if (res.text()) { 
     body = res.json(); 
    } 

    return body || {}; 
} 
} 

登录组件

import { Component, OnInit } from '@angular/core'; 
import {Router} from '@angular/router'; 
import {LoginService} from '../login.service'; 
@Component({ 
    selector: 'login', 
    templateUrl: './login.component.html', 
    styleUrls: ['./login.component.css'] 
}) 
export class LoginComponent implements OnInit { 


constructor(private loginService: LoginService, private router: Router) { 

    } 

    ngOnInit() { 
    } 

    login(username: string, password:string) { 

    this.loginService.login(username, password).then((res)=> { 
     if(res) { 

    this.router.navigate(['/members']); 
     //console.log('valid user'); 
     } 
     else { 
     console.log('Invalid user'); 
     } 
    });} 

} 
+0

什么是'如果(data.success)'这里?成功来自哪里? ' –

+0

我有一个spring后端,其实我跟着这个[tutorial](http://tphangout.com/angular-2-authentication-using-the-new-router/) – SuperGirl

回答

0

找到此问题的解决方法,这里是我的服务做了更改:

return new Promise((resolve) => { 
     this.http.post('http://localhost:8080/StudentManager/login', creds, { headers: headers }) 
     .map(this.extractData) 
    .toPromise()//convert to promise 
     .then(//use then instead of subscribe to form promise chain 
      success => { 
        if(success) { 
       window.localStorage.setItem('auth_key', success.data); 
       console.log('hi'); 
       this.isAuthenticated = true; 
        } 
       resolve(this.isAuthenticated); 
      }); 

    } 
    ); 
0

你似乎是混合ObservablesPromises。如果你想使用的承诺,那么你可以很容易地转换可观察到使用Observable.toPromise()。尝试一个承诺:

import 'rxjs/add/operator/toPromise'; 
//.... 

return new Promise((resolve) => { 
this.http.post('http://localhost:8080/StudentManager/login', creds, { headers: headers }) 
     .map(this.extractData) 
     .toPromise()//convert to promise 
     .then(//use then instead of subscribe to form promise chain 
      data => { 
        if(data.success) { 
       window.localStorage.setItem('auth_key', data.token); 
       console.log('hi'); 
       this.isAuthenticated = true; 
        } 
       resolve(this.isAuthenticated); 
      }); 

    } 
    ); 
    } 

更改this.extractData

private extractData(res: Response) { 
    let body; 

    // check if empty, before call json 
    if (res.json()) { 
     body = res.json(); 
    } 

    return body || {}; 
} 

res.text()是文本响应。

+0

import ..'import'rxjs /添加/运营商/ toPromise';' –

+0

我仍然有相同的结果,它显示无效的用户 – SuperGirl

+0

好的..我将编辑我的答案..它就是这样 –