Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用angular和HTTP理解rxjs_Http_Angular_Rxjs - Fatal编程技术网

使用angular和HTTP理解rxjs

使用angular和HTTP理解rxjs,http,angular,rxjs,Http,Angular,Rxjs,我正准备使用angular 2和rxjs,我遇到了一个问题 我正在尝试进行基本登录:以下是代码: class LoginPage{ ctor(private auth:AuthService) {} login(cred) { this.auth.login(cred).subscribe( res=> this.navigateToHome() } } class AuthService { ctor(private http:Auth

我正准备使用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
对象,而不是
可观察的
,因此,如果使用
login
函数并对其进行如下重构,则该功能将无法工作:

login(cred) {
   var obs = this.http.post(url, cred)
   obs.subscribe(res=> this.onLoginSuccess())
   retrun obs
 }
这会导致http请求调用两次

因此,我的问题是:我如何在我的
loginPage
中知道调用
onloginsucess
的订阅者已经完成了

如何避免2次请求?

如何

如果需要订阅
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
有什么区别?