第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從http.request()正確捕獲異常?

如何從http.request()正確捕獲異常?

慕婉清6462132 2019-11-11 10:49:04
我的部分代碼:import {Injectable} from 'angular2/core';import {Http, Headers, Request, Response} from 'angular2/http';import {Observable} from 'rxjs/Observable';import 'rxjs/add/operator/map';@Injectable()export class myClass {  constructor(protected http: Http) {}  public myMethod() {    let request = new Request({      method: "GET",      url: "http://my_url"    });    return this.http.request(request)      .map(res => res.json())      .catch(this.handleError); // Trouble line.                                 // Without this line code works perfectly.  }  public handleError(error: Response) {    console.error(error);    return Observable.throw(error.json().error || 'Server error');  }}myMethod() 在瀏覽器的控制臺中產(chǎn)生異常:原來的例外:TypeError:this.http.request(...)。map(...)。catch不是函數(shù)
查看完整描述

3 回答

?
慕標琳琳

TA貢獻1830條經(jīng)驗 獲得超9個贊

也許您可以嘗試在導(dǎo)入中添加以下內(nèi)容:


import 'rxjs/add/operator/catch';

您也可以這樣做:


return this.http.request(request)

  .map(res => res.json())

  .subscribe(

    data => console.log(data),

    err => console.log(err),

    () => console.log('yay')

  );

每個評論:


例外:TypeError:Observable_1.Observable.throw不是函數(shù)

同樣,為此,您可以使用:


import 'rxjs/add/observable/throw';


查看完整回答
反對 回復(fù) 2019-11-11
?
繁星coding

TA貢獻1797條經(jīng)驗 獲得超4個贊

更新了新服務(wù)以使用HttpClientModule和RxJS v5.5.x:


import { Injectable }                    from '@angular/core';

import { HttpClient, HttpErrorResponse } from '@angular/common/http';

import { Observable }                    from 'rxjs/Observable';

import { catchError, tap }               from 'rxjs/operators';

import { SomeClassOrInterface}           from './interfaces';

import 'rxjs/add/observable/throw';


@Injectable() 

export class MyService {

    url = 'http://my_url';

    constructor(private _http:HttpClient) {}

    private handleError(operation: String) {

        return (err: any) => {

            let errMsg = `error in ${operation}() retrieving ${this.url}`;

            console.log(`${errMsg}:`, err)

            if(err instanceof HttpErrorResponse) {

                // you could extract more info about the error if you want, e.g.:

                console.log(`status: ${err.status}, ${err.statusText}`);

                // errMsg = ...

            }

            return Observable.throw(errMsg);

        }

    }

    // public API

    public getData() : Observable<SomeClassOrInterface> {

        // HttpClient.get() returns the body of the response as an untyped JSON object.

        // We specify the type as SomeClassOrInterfaceto get a typed result.

        return this._http.get<SomeClassOrInterface>(this.url)

            .pipe(

                tap(data => console.log('server data:', data)), 

                catchError(this.handleError('getData'))

            );

    }

舊服務(wù),它使用了已棄用的HttpModule:


import {Injectable}              from 'angular2/core';

import {Http, Response, Request} from 'angular2/http';

import {Observable}              from 'rxjs/Observable';

import 'rxjs/add/observable/throw';

//import 'rxjs/Rx';  // use this line if you want to be lazy, otherwise:

import 'rxjs/add/operator/map';

import 'rxjs/add/operator/do';  // debug

import 'rxjs/add/operator/catch';


@Injectable()

export class MyService {

    constructor(private _http:Http) {}

    private _serverError(err: any) {

        console.log('sever error:', err);  // debug

        if(err instanceof Response) {

          return Observable.throw(err.json().error || 'backend server error');

          // if you're using lite-server, use the following line

          // instead of the line above:

          //return Observable.throw(err.text() || 'backend server error');

        }

        return Observable.throw(err || 'backend server error');

    }

    private _request = new Request({

        method: "GET",

        // change url to "./data/data.junk" to generate an error

        url: "./data/data.json"

    });

    // public API

    public getData() {

        return this._http.request(this._request)

          // modify file data.json to contain invalid JSON to have .json() raise an error

          .map(res => res.json())  // could raise an error if invalid JSON

          .do(data => console.log('server data:', data))  // debug

          .catch(this._serverError);

    }

}

我現(xiàn)在使用.do()(進行調(diào)試)。 .tap()


當發(fā)生服務(wù)器錯誤時,我從正在使用的服務(wù)器(精簡服務(wù)器)獲取body的Response對象的內(nèi)容僅包含文本,因此我err.text()在上面使用的原因而不是在err.json().error。您可能需要為服務(wù)器調(diào)整該行。


如果res.json()由于無法解析JSON數(shù)據(jù)而引發(fā)錯誤,_serverError則不會獲取Response對象,因此進行instanceof檢查的原因。


在此plunker,更改url為,./data/data.junk以生成錯誤。


兩種服務(wù)的用戶都應(yīng)具有可以處理該錯誤的代碼:


@Component({

    selector: 'my-app',

    template: '<div>{{data}}</div> 

       <div>{{errorMsg}}</div>`

})

export class AppComponent {

    errorMsg: string;

    constructor(private _myService: MyService ) {}

    ngOnInit() {

        this._myService.getData()

            .subscribe(

                data => this.data = data,

                err  => this.errorMsg = <any>err

            );

    }

}


查看完整回答
反對 回復(fù) 2019-11-11
  • 3 回答
  • 0 關(guān)注
  • 1768 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號