Angular2 handling http response

前端 未结 3 2124
执念已碎
执念已碎 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: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) }
    )
    

提交回复
热议问题