This is my code :
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');
}
}
The whole of my getCountries method red lines, but as soon as I comment out the catch all the red lines go.
whether I leave the catch line commented out or not. Then in the component where I want to use the method:
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);
}
}
red lines on the country => of subscribe
I have found that if I declare my getCountries Method without Observable then all the red lines go:
getCountries() {
return this.http.get(this._countriesUrl)
.map((response: Response) => <ICountry[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
So Why cant it be observable?
what if you try wth something like this:
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');
});
hope it helps
尝试这样做
.catch(err => this.handleError(err));
try below code--
this.bbService.getDetails()
.subscribe((success) => {
console.log(success);
}, (error) => {
console.log('error---',error);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.