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