2017-03-21 2 views
1

J'ai un service pour authentifier mon utilisateur, mais je ne sais pas pourquoi il ne va pas dans la méthode subscribe même si je mets des informations d'identification correctes.Angular2: La méthode Subscribe ne fonctionne pas

Quand je mets les informations d'identification correctes, il invalid user montrent ce qui signifie que isAuthentifiated est encore false.

Le service

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 || {}; 
} 
} 

Connexion Component

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

ce qui est 'si (data.success)' ici? d'où vient le succès? ' –

+0

J'ai un ressort de base, en fait j'ai suivi ce [tutoriel] (http://tphangout.com/angular-2-authentication-using-the-new-router/) – SuperGirl

Répondre

0

a trouvé la solution à ce problème, voici les changements que je l'ai fait dans le service:

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

Vous semblez mélanger Observables et Promises. Si vous voulez utiliser des promesses, vous pouvez facilement convertir un Observable à une promesse en utilisant Observable.toPromise() .Essayez:

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); 
      }); 

    } 
    ); 
    } 

Changer votre this.extractData

private extractData(res: Response) { 
    let body; 

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

    return body || {}; 
} 

res.text() est pour les réponses textuelles.

+0

l'importer ..' import 'rxjs/add/operator/toPromise '; ' –

+0

J'ai encore le même résultat, il montre l'utilisateur invalide – SuperGirl

+0

ok .. Je vais éditer ma réponse .. de cette façon –