简体   繁体   中英

Angular2 : Subscribe method is not working

I have a service to authenticate my user, but I don't know why it doesn't go inside the subscribe method even if I put correct credentials .

When I put correct credentials it show invalid user which means that isAuthentifiated is still false .

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

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

}

You seem to be mixing Observables and Promises . If you want to use promises, then you can easily convert an Observable to a promise using Observable.toPromise() .Try:

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

    }
    );
  }

Change your this.extractData

private extractData(res: Response) {
    let body;

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

    return body || {};
}

res.text() is for text responses.

Found the solution for this issue , here is the changes that I did in the 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);
            });

    }
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM