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


i creating service angular2. have used http.post method return eventemmiter , per documentation have passed next , return lambdas. https://angular.io/docs/js/latest/api/http/http-class.html

next lambda working expected return lambda not @ called.

when try return this.user. null since post operation not yet complete. should wait before auth response back.

and if choose reactive programming , want return rx.observable return of method. how can create rx.observable subscribe 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 how attached string observable 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 ui component calling loginservice

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

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -