Reputation: 12483
I have this asynchronous function which uses http.get inside a promise.
private _getSchema(fileName): any {
return new Promise((resolve, reject) => {
this.http.get(fileName)
.map(this._extractData)
.catch(this._handleError)
.subscribe(schema => resolve(schema));
});
};
Rather than call this._handleError in the catch block, I would like to reject my promise and pass reject the error object. How do I do that?
attempt:
private _getSchema(fileName): any {
return new Promise((resolve, reject) => {
this.http.get(fileName)
.map(this._extractData)
.catch(err => reject(err))
.subscribe(schema => resolve(schema));
});
};
gives error:
Argument of type '(err: any) => void' is not assignable to parameter of type '(err: any, caught: Observable) => ObservableInput<{}>'. Type 'void' is not assignable to type 'ObservableInput<{}>'.
I'm using typescript
Upvotes: 0
Views: 958
Reputation: 29936
Promises fit better as http results than observables, so I suggest you to go the promise way:
private _getSchema(fileName): any {
return this.http.get(fileName).toPromise().then(x => this._extractData(x));
};
The way you tried does not work because Observable.prototype.catch
has a different signature (It needs to provide a new observable to continue with). Subscribing to onError is what you were searching for:
private _getSchema(fileName): any {
return new Promise((resolve, reject) => {
this.http.get(fileName)
.map(this._extractData)
.subscribe(resolve, reject);
});
};
But this is exactly what observable.toPromise()
does.
Upvotes: 2