observable上的Angular 2 catch会导致错误:

时间:2017-01-04 13:58:50

标签: angular

这是我的代码:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { ICountry } from '../interfaces/country';

@Injectable()
export class RecruiterService {
private _countriesUrl = '/countries.json';


constructor(private http: Http) { }

getCountries(): Observable<ICountry[]> {
    return this.http.get(this._countriesUrl)
        .map((country: Response) => <ICountry[]> country.json())
        .do(data => console.log('All: ' + JSON.stringify(data)))
        .catch(this.handleError);
}

 private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
}
}

我的整个getCountries方法都是红线,但是一旦我注释掉了所有的红线就行了。

我是否将捕获线注释掉。然后在我想要使用该方法的组件中:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { ICountry } from '../services/interfaces/country';
import { RecruiterService } from '../services/recruiter/recruiter.service';

@Component({
selector: 'agent-details',
templateUrl: 'agent-details.component.html',

providers : [RecruiterService]
})
   export class AgentDetailsComponent implements OnInit {
   private country: ICountry[] = [];
   private errorMessage: string;

   constructor(private recruiterService : RecruiterService) {

   } 

   ngOnInit(): void {
    this.recruiterService.getCountries()
        .subscribe(
        country => this.country = <any>country,
            error => this.errorMessage = error);
   }
}

国家/地区的红线 =&gt;订阅

我发现如果我声明没有Observable的getCountries方法,那么所有的红线都会出现:

 getCountries()  {
    return this.http.get(this._countriesUrl)
        .map((response: Response) => <ICountry[]> response.json())
        .do(data => console.log('All: ' + JSON.stringify(data)))
        .catch(this.handleError);
}

那么为什么它不能被观察到呢?

3 个答案:

答案 0 :(得分:0)

如果你尝试这样的话会怎么样:

 public GetAll = (): Observable<ICountry[]> => {
        return this._http.get(this.actionUrl).map((response: Response) => <ICountry[]>response.json());
    }



    public countries: ICountry[]=[]

    this._dataService
            .GetAll()
            .subscribe(data => this.countries = data,
            error => (response) => {
                //this._toasterService.pop('error', 'Damn', 'Something went wrong...');
            },
            () => {
                //this._toasterService.pop('success', 'Complete', 'Getting all countries complete');

            });

希望有所帮助

答案 1 :(得分:0)

尝试这样做

MediaElement

答案 2 :(得分:0)

尝试下面的代码-

this.bbService.getDetails()
      .subscribe((success) => {
        console.log(success);
      }, (error) => {
        console.log('error---',error);
    });