user348173 user348173 - 1 month ago 10
TypeScript Question

Angular 2, Observables - return some data from subscribe

I have a login component and a simple method:

login(event) {
event.preventDefault();
this.authService.login(this.user);
}


This is my
AuthService
:

export class AuthService {
constructor(private jsonApiService:JsonApiService) {
}

isLoggedIn: boolean = false;

login(user:User): any {
this.jsonApiService.post('/token', user)
.subscribe(
resp => {
check if success,
store token to localstorage,
set isLoggedIn = true
* return new object with data about success/error


},
err => {
handle error
* return new object with data about success/error
});
}

logout(): void {
this.isLoggedIn = false;
}
}


This code works fine. I get response, but I am wondering how to return some data from service to component. I don't want to move subscribe to component, because, I believe, handling must be in the AuthService.

Answer

Since the http request runs async, you can't return something from inside the lambda, but you could pass a callback like this (which would be essentially like the subscribe):

login(user: User, onSuccess: (data) => void, onError: (data) => void = null): any {
    this.jsonApiService.post('/token', user)
        .subscribe(
            resp => {
               check if success,
               store token to localstorage,
               set isLoggedIn = true

               onSuccess(/*somedata*/);
            },
            err => {    
               handle error

               if (onError)
                   onError(/*somedata*/);
            });
}

And then in your component:

login(event) {       
    event.preventDefault();
    this.authService.login(this.user, (data) => {
        // do something here with the data
    });    

    // or optionally with onError callback
    this.authService.login(this.user, (data) => {
        // do something here with the data
    },
    (errData) => {
        // do something with the error
    });      
}
Comments