Angular2:订阅方法不起作用

时间:2017-03-21 08:49:16

标签: angular authentication typescript 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');
      }
    });}

}

2 个答案:

答案 0 :(得分:0)

您似乎在混合ObservablesPromises。如果你想使用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()用于文本回复。

答案 1 :(得分: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);
            });

    }
    );