【问题标题】:Understanding rxjs with angular and HTTP用 Angular 和 HTTP 理解 rxjs
【发布时间】:2016-03-24 20:06:16
【问题描述】:

我想使用 angular 2 和 rxjs,但我遇到了问题。

我正在尝试进行基本登录:这是代码:

class LoginPage{
    ctor(private auth:AuthService) {}

    login(cred) {
        this.auth.login(cred).subscribe( res=> this.navigateToHome()
    }
}

class AuthService {
    ctor(private http:AuthHttp) {}

    login(cred){
        return this.http.post(url, cred).subscribe(res => this.onLoginSuccess())

     }
}

class AuthHttp extends Http {
   ctor (.....)

   post(...) {
     // Add some headers
      return super.post(..)
   }
}

首先,由于AuthService 中的login 现在返回Subscription 对象而不是Observable,因此首先将无法工作,另外,如果采用login 函数并像这样重构它:

login(cred) {
   var obs = this.http.post(url, cred)
   obs.subscribe(res=> this.onLoginSuccess())
   retrun obs
 }

这会导致 http 请求调用两次..

所以我的问题是:我怎么知道我的loginPage 调用onLoginSuccess 的订阅者已经完成了?

如何避免两次请求?

【问题讨论】:

    标签: http angular rxjs


    【解决方案1】:

    share() 呢?

    如果您需要订阅AuthService.login(),则login() 必须返回Observable。但是您还需要在AuthService 内登录时做一些事情,不是吗? share() 让您在登录时订阅AuthService 并返回Observable

    class AuthService {
        ctor(private http:AuthHttp) {}
    
        login(cred){
            var result = this.http.post(url, cred).share();
            result.subscribe(res => this.onLoginSuccess())
            return result;
         }
    }
    

    【讨论】:

    • 可以分享更多细节吗?这和do有什么区别?
    猜你喜欢
    • 2021-05-26
    • 2019-06-05
    • 2016-07-06
    • 2018-04-19
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    相关资源
    最近更新 更多