Angular 2,Observables - 从subscribe返回一些数据

use*_*173 2 rxjs typescript angular

我有一个登录组件和一个简单的方法:

login(event) {       
    event.preventDefault();
    this.authService.login(this.user);       
}
Run Code Online (Sandbox Code Playgroud)

这是我的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码工作正常.我得到了回应,但我想知道如何将一些数据从服务返回到组件.我不想移动订阅组件,因为,我相信,处理必须在AuthService中.

rin*_*usu 5

由于http请求运行异步,你不能从lambda内部返回一些东西,但你可以传递这样的回调(这基本上就像订阅):

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*/);
            });
}
Run Code Online (Sandbox Code Playgroud)

然后在你的组件中:

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
    });      
}
Run Code Online (Sandbox Code Playgroud)