Angular2 handling http response

前端 未结 3 2110
执念已碎
执念已碎 2020-11-27 14:19

I just have a question regarding structuring and handling responses from http requests within a service. I am using Angular2.alpha46 Typescript ( Just start

相关标签:
3条回答
  • 2020-11-27 14:42

    Update alpha 47

    As of alpha 47 the below answer (for alpha46 and below) is not longer required. Now the Http module handles automatically the errores returned. So now is as easy as follows

    http
      .get('Some Url')
      .map(res => res.json())
      .subscribe(
        (data) => this.data = data,
        (err) => this.error = err); // Reach here if fails
    

    Alpha 46 and below

    You can handle the response in the map(...), before the subscribe.

    http
      .get('Some Url')
      .map(res => {
        // If request fails, throw an Error that will be caught
        if(res.status < 200 || res.status >= 300) {
          throw new Error('This request has failed ' + res.status);
        } 
        // If everything went fine, return the response
        else {
          return res.json();
        }
      })
      .subscribe(
        (data) => this.data = data, // Reach here if res.status >= 200 && <= 299
        (err) => this.error = err); // Reach here if fails
    

    Here's a plnkr with a simple example.

    Note that in the next release this won't be necessary because all status codes below 200 and above 299 will throw an error automatically, so you won't have to check them by yourself. Check this commit for more info.

    0 讨论(0)
  • 2020-11-27 14:44

    The service :

    import 'rxjs/add/operator/map';
    
    import { Http } from '@angular/http';
    import { Observable } from "rxjs/Rx"
    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class ItemService {
      private api = "your_api_url";
    
      constructor(private http: Http) {
    
      }
    
      toSaveItem(item) {
        return new Promise((resolve, reject) => {
          this.http
            .post(this.api + '/items', { item: item })
            .map(res => res.json())
            // This catch is very powerfull, it can catch all errors
            .catch((err: Response) => {
              // The err.statusText is empty if server down (err.type === 3)
              console.log((err.statusText || "Can't join the server."));
              // Really usefull. The app can't catch this in "(err)" closure
              reject((err.statusText || "Can't join the server."));
              // This return is required to compile but unuseable in your app
              return Observable.throw(err);
            })
            // The (err) => {} param on subscribe can't catch server down error so I keep only the catch
            .subscribe(data => { resolve(data) })
        })
      }
    }
    

    In the app :

    this.itemService.toSaveItem(item).then(
      (res) => { console.log('success', res) },
      (err) => { console.log('error', err) }
    )
    
    0 讨论(0)
  • 2020-11-27 14:56

    in angular2 2.1.1 I was not able to catch the exception using the (data),(error) pattern, so I implemented it using .catch(...).

    It's nice because it can be used with all other Observable chained methods like .retry .map etc.

    import {Observable} from 'rxjs/Rx';
    
    
      Http
      .put(...)
      .catch(err =>  { 
         notify('UI error handling');
         return Observable.throw(err); // observable needs to be returned or exception raised
      })
      .subscribe(data => ...) // handle success
    

    from documentation:

    Returns

    (Observable): An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.

    0 讨论(0)
提交回复
热议问题