2
votes

I am creating a service an Angular2. I have used the http.post method which return a EventEmmiter and as per the documentation I have passed next and return lambdas. https://angular.io/docs/js/latest/api/http/Http-class.html

next lambda is working as expected but return lambda is not at all called.

When I try to return this.user. It is null since post operation is not yet complete. What should I do to wait before the auth response is back.

And if I choose to do reactive programming and want to return a Rx.Observable as return of this method. How can I create this Rx.Observable which will subscribe to http post observable complete event.

@Injectable()
export class LoginService {

  http:Http;
  headers:Headers;
  user:User;

  constructor(http: Http) {
    this.http=http;
    this.headers=new Headers();
    this.headers.set('Content-Type','application/json');
    this.user = new User();
  }

  authenticateUser(credential:Credential) {
    credential.type = 'normal';
    this.http.post('http://localhost:8000/api/v1/auth',
      JSON.stringify(credential),
      {
        headers: this.headers
      }
    ).observer({
      next: (res) => {
        if(res.json()._error_type){
          console.log('Error Occured');
        }
        console.log(res.json());
        this.user.authToken = res.json().auth_token;
      },
      return: () => {
        console.log("Logged In");
        return "LoggedIn Success"
      }}
    );
    console.log(this.user);
    return this.user;
  }
}

export class User{
  authToken:String;
}

export class Credential{
  username:string;
  password:string;
  type:string;
}
1
Hey there, this seems to be fixed on alpha33, see changelog and thisEric Martinez
I am using alpha33, however I did found out how to conver one observable to other. Thanks :)Badal Singh

1 Answers

2
votes

This is how I attached string observable to http call response

  authenticateUser(credential:Credential):Rx.Observable<string> {
    credential.type = 'normal';
    return Rx.Observable.create<string>(
      observer => {
        var val:String;
        this.http.post('http://localhost:8000/api/v1/auth',
          JSON.stringify(credential),
          {
            headers: this.headers
          }
        ).toRx().map(res => res.json()).subscribe(
        (res) => {
          if(res._error_type){
            console.log('Error Occured');
            observer.onError('ErrorOccured');
          } else {
            this.user = new User();
            this.user.authToken = res.auth_token;
            observer.onNext('LoginSuccess');
          }
          observer.onCompleted();
        });
        return () => console.log('disposed')
      }
    );
  }

Here is the UI Component which was calling LoginService

this.loginService.authenticateUser(credential).subscribe(val => {console.log('result:' + val)});