首页 文章

如何链接/组合Observable

提问于
浏览
1

好吧,这已经困扰了我一段时间,想知道是否有人能告诉我在多个服务之间链接Observable的好方法 .

在下面Auth类的例子中,从 this.api.postSignIn() 创建一个Observable的好方法是什么,所以 signInSubmit() 可以在组件中订阅它?值得注意的是 this.api.postSignIn() 正在订阅Angular2 http请求 .

这有点像反模式,是否有更好的方法来做到这一点?

基本上我想要实现的功能是:

  • 组件 - 负责收集登录数据并以正确的格式将其发送到身份验证服务 . 然后,在Auth登录完成后,导航到管理页面 .

  • 服务 - 进行api调用以获取令牌,通过令牌服务设置令牌并设置 isSignedIn bool然后将控制权推迟回调用组件 .

@Component({...})
export class SignIn {
   private signIn:SignInModel = new SignInModel();

    constructor(private auth:Auth, private router:Router) {
    }

    ngOnInit() {
    }

    signInSubmit() {
        this.auth.signIn(this.signIn)
            .subscribe(
                () => {
                    this.router.navigate(['/admin']);
                }
           )
    }

}

@Injectable()
export class Auth {
    private isSignedIn:boolean = false;

    constructor(private api:Api, private tokenService:TokenService) {

    }

    public signIn(signIn:SignInModel) {

       return this.api.postSignIn(signIn)
            .subscribe(
                response => {
                    this.tokenService.set(new TokenModel(response.token));
                    this.isSignedIn = true;
                },
                error => {
                    console.log(error);
                }
            );
    }

    public signOut() {

   }
}

1 回答

  • 2

    我会利用 docatch 运算符而不是 signIn 方法中的订阅 .

    这是重构的 signIn 方法:

    public signIn(signIn:SignInModel) {
       return this.api.postSignIn(signIn)
            .do(
                response => {
                    this.tokenService.set(new TokenModel(response.token));
                    this.isSignedIn = true;
                })
            .catch(
                error => {
                    console.log(error);
                }
            );
    }
    

    在您的情况下,您无法订阅此方法的返回对象,因为 subscribe 方法返回订阅而不是可观察的 . 所以你不能订阅它...

相关问题