Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从http.request()正确捕获异常?_Http_Typescript_Angular_Observable - Fatal编程技术网

如何从http.request()正确捕获异常?

如何从http.request()正确捕获异常?,http,typescript,angular,observable,Http,Typescript,Angular,Observable,我的部分代码: myMethod()在浏览器控制台中产生异常: 原始异常:TypeError:this.http.request(…).map(…).catch不是函数 也许您可以尝试在导入中添加以下内容: import 'rxjs/add/operator/catch'; 您还可以执行以下操作: return this.http.request(request) .map(res => res.json()) .subscribe( data => consol

我的部分代码:

myMethod()
在浏览器控制台中产生异常:

原始异常:TypeError:this.http.request(…).map(…).catch不是函数


也许您可以尝试在导入中添加以下内容:

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不是函数 同样,为此,您可以使用:

import 'rxjs/add/observable/throw';

RxJS函数需要专门导入。一个简单的方法是从“rxjs/Rx”


然后确保访问
Observable
类作为
Rx.Observable

新服务更新以使用HttpClientModule,并:

我使用
.do()
()进行调试

当出现服务器错误时,我从正在使用的服务器(lite server)获取的
响应
对象的
主体
仅包含文本,因此我使用上面的
err.text()
而不是
err.json().error
。您可能需要为服务器调整该行

如果
res.json()
由于无法解析json数据而引发错误,
\u serverError
将不会获得
响应
对象,因此需要检查
instanceof
的原因

在这种情况下,将
url
更改为
/data/data.junk
以生成错误


任何一项服务的用户都应具有可处理错误的代码:

@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
            );
    }
}
@组件({
选择器:“我的应用程序”,
模板:'{data}}
{{errorMsg}}`
})
导出类AppComponent{
errorMsg:string;
构造函数(私有_myService:myService){}
恩戈尼尼特(){
这是。_myService.getData()
.订阅(
data=>this.data=data,
err=>this.errorMsg=err
);
}
}

在最新版本的angular4中使用

import { Observable } from 'rxjs/Rx'

它将导入所有必需的内容。

有几种方法可以做到这一点。两者都很简单。每一个例子都非常有效。您可以将其复制到项目中并进行测试

第一种方法更可取,第二种方法有点过时,但到目前为止它也能工作

1) 解决方案1

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
})
export class AppModule { }



// File - product.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
import { catchError, tap } from 'rxjs/operators'; // Important! Be sure to connect operators

// There may be your any object. For example, we will have a product object
import { ProductModule } from './product.module';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: HttpClient, private product: ProductModule){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will get into catchError and catch them.
    getProducts(): Observable<ProductModule[]>{
        const url = 'YOUR URL HERE';
        return this.http.get<ProductModule[]>(url).pipe(
            tap((data: any) => {
                console.log(data);
            }),
            catchError((err) => {
                throw 'Error in source. Details: ' + err; // Use console.log(err) for detail
            })
        );
    }
}

谢谢你的帮助,很有效。之后,我对
throw()
函数也有同样的问题。我添加了这一行
import'rxjs/Rx'取而代之。现在所有操作符都正常工作了。您是否模拟了一个错误以查看
.catch
是否真的有效?
.subscribe()
确实有效。是的,第二个问题是
异常:TypeError:Observable\u 1.Observable.throw不是一个函数
。正如我前面所说的,它可以用@MattScarpino-answer或这个plunker中的maner来修复:也可以导入throw:
import'rxjs/add/observable/throw'并且不要导入所有内容,它太大了。很好的解决方案,,非常有用,我可能会添加(err)类型为ResponseRxjs是一个非常大的文件,如果你导入所有内容,它将增加你的加载时间如果你只需要一两个操作符,你不应该从Rxjs导入所有内容。不要这样做,它将导入所有RXJ,因此将导致捆绑包大小增加!
@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
            );
    }
}
import { Observable } from 'rxjs/Rx'
// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
})
export class AppModule { }



// File - product.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
import { catchError, tap } from 'rxjs/operators'; // Important! Be sure to connect operators

// There may be your any object. For example, we will have a product object
import { ProductModule } from './product.module';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: HttpClient, private product: ProductModule){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will get into catchError and catch them.
    getProducts(): Observable<ProductModule[]>{
        const url = 'YOUR URL HERE';
        return this.http.get<ProductModule[]>(url).pipe(
            tap((data: any) => {
                console.log(data);
            }),
            catchError((err) => {
                throw 'Error in source. Details: ' + err; // Use console.log(err) for detail
            })
        );
    }
}
// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
})
export class AppModule { }



// File - product.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: Http){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will to into catch section and catch error.
    getProducts(){
        const url = '';
        return this.http.get(url).map(
            (response: Response) => {
                const data = response.json();
                console.log(data);
                return data;
            }
        ).catch(
            (error: Response) => {
                console.log(error);
                return Observable.throw(error);
            }
        );
    }
}