[英]Angular2 : Subscribe method is not working
我有一個服務來驗證我的用戶,但我不知道為什么它不會進入subscribe方法,即使我輸入正確的憑據。
當我輸入正確的憑據時,它顯示
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');
}
});}
}
你似乎在混合Observables
和Promises
。 如果你想使用promises,那么你可以使用Observable.toPromise()
輕松地將Observable轉換為promise。嘗試:
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()
用於文本響應。
找到此問題的解決方案,這是我在服務中所做的更改:
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);
});
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.