【问题标题】:Perform action when http resolves and throw error if needed在 http 解析时执行操作并在需要时抛出错误
【发布时间】:2017-07-22 16:51:06
【问题描述】:

我正在尝试使用 observables 执行以下操作,但我不知道最好的方法是什么:

我正在使用 http 调用登录端点。该服务将返回一个令牌。我想从 APP 内的 2 个不同点依次执行 2 个不同的操作:当 http 解析时,我需要存储提供的令牌,然后显示一条消息。我尝试了以下方法:

return this.http.get(this.config.getApi('login'), params)
           .map(response => response.json())
           .do((data) => {
               // Store token here
               // If it fails, throw error
               // Tried Observable.throw here but the subscriber doesn't get it.
            }).subscribe(
               (data) => {
                  // Everything went fine
                },
               () => {
                  // Either the http request failed or 
                 // the process of storing the token threw an error.
            }
       );

不幸的是,除非 http 调用失败,否则返回的 observable 的订阅者永远不会出错。我应该使用什么运算符而不是 do?

谢谢。

【问题讨论】:

    标签: angular http rxjs


    【解决方案1】:

    您应该是subscribing 才能访问回复

    this.http.get(this.config.getApi('login'), params)
                    .map(response => response.json())
                    .subscribe(data=>{
                         console.log(data);
           });
    

    【讨论】:

    • 我想做的是运行代码来存储我的令牌,然后返回 observable 以便其他人可以订阅。如果令牌存储操作失败,订阅该 observable 的方法应该会出错。忘记将订阅添加到我的示例中。
    • 你想把它存储在哪里?为什么?你是问在 do 或里面抛出一个错误??
    【解决方案2】:

    据我了解,您想这样做:

    do http call 
        then do something else 
           if error   
               throw error
        subscribe 
            handle success
            handle error 
    

    我能想到的一种方法是使用 flatMap 。重写你的代码

    return this.http.get(this.config.getApi('login'), params)
           .map(response => response.json())
           .flatMap((data) => {
               //do whatever you want to do , 
               // lets say error = true if something went wrong
               return error ? 
                   Observable.throw('error message') :
                   Observable.of(data);
            }).subscribe(...);
    

    JSBIN 带有简单插图的链接

    【讨论】:

    • 就是这样。谢谢!
    【解决方案3】:

    也许是这样的?

    import { isDevMode } from '@angular/core';
    import { _throw } from 'rxjs/observable/throw';
    
    
    return this.http.get(this.config.getApi('login'), params)
    .map(r => r.json())
    .do(data => {
      this.token = data; //an instance variable defined in your service class
      if(isDevMode()) console.log(data) // display log only in devMode (why would you want to log something in console in production?! :D)
    })
    .catch(error => _throw(JSON.stringify(error));
    

    您需要从外部(组件、守卫等)调用此方法,以便执行 http 请求

    【讨论】:

    • 那么你可以在do里面添加条件
    猜你喜欢
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多