首页 > 解决方案 > Rxjs observable 被订阅了两次

问题描述

我从 rxjs 库开始,尝试向 API REST 发出请求。我得到的问题是里面的代码subscribe被执行了两次,但只被调用了一次

observable方法,observable从一个promise

post(url, body): Observable<Response> {
    return from(fetch(url, {
       method: 'POST',
       body: JSON.stringify(body),
       headers: {
          'Accept': 'application/json, text/plain',
          'Content-Type': 'application/json;charset=UTF-8'
       }
     }))
 }

然后,我用来读取流值的代码是:(我已经检查过,它只被调用一次)

doLogin(){
    var creds={
        "email":"user@gmail.com",
        "password":"user"
    }
    var stream$ =this.httpService.post("http://localhost:8080/api/login",creds)
    stream$.subscribe(x=>console.log(x))
}

我在导航器控制台中看到的console.log()结果是 2 和 fetch 响应的结果

标签: reactjsrxjsobservablereactive-programmingreactive

解决方案


我认为在订阅函数中实际发生的是,您定义当您从流中接收到新值时要做什么。这意味着 subscribe 实际上并没有被执行两次,而是两次接收一个值。


推荐阅读