0

Enviroment AngularJS 4

I try to run a HTTP Request in a function, but i can not send the result back. Beloow have post my code with some comments. I just need the true or false value but i receive nothing.

I struggling with this issue for a while and don't find a explaination and solution. Does someone can give me a hint?

public runLoginProcess(username:String, password:String):boolean{

    let body= { "username":username,"password":password };
    let head = new Headers();
    head.append("Content-Type", "application/json");
    head.append("Accept", "application/json");

// RUN THE HTTP CALL AN IF IT WORKS, SEND TRUE AND ERROR IN CASE OF AN ERROR BACK
    this.http.post("<PATH TO MY SERVICE>", body)
      .subscribe(response => {
          let token = response.json() && response.json().token;
          if (token) {
            localStorage.setItem('currentUser', JSON.stringify({"username": username, "token": token}))
            return true;
          }
        },
        error2 => {
          return false;
        }
      );
  }
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
michael-mammut
  • 2,595
  • 5
  • 28
  • 46
  • Possible duplicate of [Node.js promises, async, or just callbacks](https://stackoverflow.com/questions/25133942/node-js-promises-async-or-just-callbacks). You have to use some sort of async construct: callbacks, pomises, or now await. – Robert Moskal Jul 29 '17 at 19:47
  • Are you expecting runLoginProcess to return the true/false result? I suspect you're expecting a synchronous behaviour from an inherently asynchronous function. Try using your debugger, or try putting a console.log right after your call to http.post, and also put a console.log call right before your return true/return false statements. Perhaps put a delay in your HTTP service if you control it. Then observe the order of execution. – struthersneil Jul 29 '17 at 19:51
  • This is Angular, not AngularJS. There's no such thing as AngularJS 4. – Estus Flask Jul 29 '17 at 20:00
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Estus Flask Jul 29 '17 at 20:05

1 Answers1

3

Your approach to observables is all off. your runLoginProcess function isn't returning anything, and the subscribe function shouldn't return at all. The way you should use this is more like

public runLoginProcess(username:String, password:String):Observable<boolean>{

    let body= { "username":username,"password":password };
    let head = new Headers();
    head.append("Content-Type", "application/json");
    head.append("Accept", "application/json");

// RUN THE HTTP CALL AN IF IT WORKS, SEND TRUE AND ERROR IN CASE OF AN ERROR BACK
    return this.http.post("<PATH TO MY SERVICE>", body)
      .map(response => {
          let token = response.json() && response.json().token;
          if (token) {
            localStorage.setItem('currentUser', JSON.stringify({"username": username, "token": token}))
            return true;
          } else {
             return false;
          }
        }
      )
      .catch(err => Observable.of(false)); //this line isn't needed, but just if you don't want to error handle at the caller's subscription, you can intercept them here and map to a false value.
  }
  
  
  
  var loggedIn;
  
   this.runLoginProcess().subscribe(
      (val) => this.loggedIn = val
    );
  
  

This way, you take the response from your post, map it into a boolean value, return that observable sequence to the caller, then the caller subscribes to the observable and receives the boolean value in the subscription.

Remember observables are just a definition of how to handle a stream of values.

bryan60
  • 28,215
  • 4
  • 48
  • 65
  • thank you for your very fast reply, but i am facing to the problem, that http.post() has no map, just a subscribe() – michael-mammut Jul 29 '17 at 20:01
  • you need to either import {Observable} from 'rxjs/Observable'; or import 'rxjs/add/operator/map'; the angular4 http client returns observables which always have a map method. If you're using a custom http client, then that is a separate issue. – bryan60 Jul 29 '17 at 20:04
  • Observable is added to this class – michael-mammut Jul 29 '17 at 20:09
  • 1
    then there is some other issue, either you're overriding the http service somewhere or there is an issue with your compiler. The http client always returns observables which always have a map method. Did you change the function return type to be Observable? and are you returning the http method exactly as I wrote it? – bryan60 Jul 29 '17 at 20:12