【问题标题】:RxJS calling second operation when first is successful第一次成功时,RxJS 调用第二次操作
【发布时间】:2016-04-06 04:17:52
【问题描述】:

我正在使用 Angular2 和 rxjs。

我有一个名为 login() 的操作。这将使用 http.post 请求将身份验证详细信息发送到服务器,然后将收到一个令牌。

它需要读取结果,如果成功接收到令牌,它将执行一些操作来验证令牌并对其进行解码,如果一切正常,则它将用户名从令牌发送到服务器,并带有http.get 并检索用户的详细信息。

我希望将以上所有内容作为一个 Observable 返回,但我对如何使用 RxJS 方式构建应该一个接一个发生的两个操作感到头疼。

我不认为订阅第一个操作然后在第一个操作中调用第二个操作是“正确”的方式,因为那你如何捕获第一个操作中的失败。

这样的?

this.http.post('http://localhost/auth/token', creds, {
    headers: headers
})
.map(res => res.json())
.do(
    // validate token
    // decode token
)
.thenDo(
    // get user details
    this.http.get(url, options)
    .map(res => res.json())
    .do(
         //save user and token in localStorage
    )
)

【问题讨论】:

    标签: rxjs observable chaining


    【解决方案1】:

    我对 Rxjs do and thenDo 函数了解不多,但是你可以这样做

     this.http.post('http://localhost/auth/token', creds, {
            headers: headers
        })
        .map(res => {
            return [{status: res.status , json: res.json()}]
            })
        .subscribe(res=>{
            if(res[0].status == 200){   // do you action depends on status code you got assuming 200 for OK response
                this.validateToken()  // Validate your token here in some  method named as validateToken
                this.decodeToken()  // decode token here in this method
                this.getUserDetail() //if everything worked fine call your another get request in another method 
            }
            },
            err => {
                console.log(err, err.status)    //catch your error here 
            })
    
            getUserDetail(){
                // make http get request for user detail and saveing into locastroage
            }
    

    【讨论】:

      【解决方案2】:

      使用flatMap 是链接操作的好方法,每个操作都返回一个新的 Promise 或 Observable。每次我们需要映射一个返回 Promise 或 Observable 的函数时,我们可以使用flatMap 构造一个发出解析数据的流。这里我们构造了一个用户数据的 Observable,最后我们可以订阅它(保存到本地存储等)。

      我假设您的验证代码只是一些返回 Promise 或 Observable 的函数。

      const options = { headers };
      const user$ = this.http.post('http://localhost/auth/token', creds, options)
        .map(res => res.json())
        .flatMap(validationFunctionThatReturnsAPromise)
        .flatMap(authResponse => {
          // get user details
          return this.http.get(url, options).map(res => res.json());
        });
      
      user$.subscribe(user => /** do something with the user data **/);
      

      【讨论】:

        猜你喜欢
        • 2012-07-31
        • 1970-01-01
        • 1970-01-01
        • 2018-10-19
        • 1970-01-01
        • 1970-01-01
        • 2019-10-20
        • 2011-10-26
        • 2016-05-25
        相关资源
        最近更新 更多