简体   繁体   中英

How to create a new Observable which is subscribed to Observable returned by http.post method in angular2?

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

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

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