问题
I'm migrating to rxjs@5.5.2 and using lettable operators... I also update Observable static methods. I wonder what is the counterpart of Observable.throw and import 'rxjs/add/observable/throw';.
Should I import ugly _throw?
import { _throw } from 'rxjs/observable/throw';
Or there's a better way. Honestly I liked static methods on Observable, and now it seems that all static creating methods like of, from should be imported from rxjs/observable/<methodName> ?
回答1:
I'm still getting my head round 5.5 but it looks like now instead of importing throw use ErrorObservable.
// import { _throw } from 'rxjs/observable/throw';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
ErrorObservable.create('error');
From this guide it looks like it has to be _throw to avoid a keyword clash (the rest of the video is good for getting started with 5.5)
回答2:
In continuation to Mick's answer, in the rxjs version 6 _throw is replaced by throwError
import {Observable, throwError} from 'rxjs';
RxJS Migration Guide
回答3:
Yes _throw is correct(this will do exactly what JayChase wrote but is less code). You do the same with of:
import {of} from 'rxjs/observable/of';
import {_throw} from 'rxjs/observable/throw';
// ...
// ...
if (result) {
return of(result as T);
} else {
return _throw('error');
}
}
回答4:
For Angular 5 and above:
import{Http} from '@angular/http';
import {HttpClient,HttpResponse,HttpErrorResponse } from '@angular/common/http';
import { Injectable} from '@angular/core'
import {Employee} from './employee';
import { Observable,throwError } from 'rxjs';
import { map,catchError } from 'rxjs/operators';
@Injectable()
export class employeeService{
constructor(private _http:Http){ }
getEmployees():Observable<Employee[]>{
return this._http.get('YOUR URL')
.pipe(
map((res: Response) => res.json()),
catchError(this.handleError)
);
//.pipe(catchError(this.handleError));
}
handleError(error:HttpErrorResponse){
console.log(error);
return throwError(error.message);
}
}
回答5:
If you wonder which one to use - ErrorObservable vs _throw, here's something from the 5.5.2 source core
RxJs library 5.5.2 - throw.ts file
import { ErrorObservable } from './ErrorObservable';
export const _throw = ErrorObservable.create;
So, it doesn't matter.
来源:https://stackoverflow.com/questions/47097606/observable-throw-replacement-in-rxjs-5-5-2