Angular2:订阅方法不起作用

Angular2 : Subscribe method is not working

我有一个服务来验证我的用户,但我不知道为什么即使我输入了正确的凭据它也没有进入订阅方法。

When I put correct credentials it show invalid user which means that isAuthentifiated is still 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');
      }
    });}

}

您似乎在混淆 ObservablesPromises。如果你想使用 promise,那么你可以使用 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);
            });

    }
    );