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 queisAuthentifiated
est encorefalse
.
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');
}
});}
}
ce qui est 'si (data.success)' ici? d'où vient le succès? ' –
J'ai un ressort de base, en fait j'ai suivi ce [tutoriel] (http://tphangout.com/angular-2-authentication-using-the-new-router/) – SuperGirl