Skip to content

Instantly share code, notes, and snippets.

@RickStrahl
Last active September 12, 2016 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RickStrahl/204de6f9e6607b79010f5e7648b0d1a7 to your computer and use it in GitHub Desktop.
Save RickStrahl/204de6f9e6607b79010f5e7648b0d1a7 to your computer and use it in GitHub Desktop.
Angular 2 HttpClient Wrapper Problems
import {Injectable} from "@angular/core";
import {Http, RequestOptionsArgs, Response} from "@angular/http";
import {UserInfo} from "./userInfo";
import {CatchSignature} from "rxjs/operator/catch";
import {Observable} from "rxjs";
/**
* Wrapper around the Http provider to allow customizing HTTP requests
*/
@Injectable()
export class HttpClient {
constructor(private http:Http, private user:UserInfo) {
}
get(url:string, requestOptions?:RequestOptionsArgs) {
this.ensureOptions(!requestOptions);
// want to return same behavior as Http provider
// error: zone.js:344 Unhandled Promise rejection: this.http.get(...).catch is not a functio
return this.http
.get(url, requestOptions)
.catch( response => {
if (response.status == 401)
this.user.isAuthenticated = false;
return response;
});
}
...
ensureOptions(requestOptions:RequestOptionsArgs):RequestOptionsArgs {
// this fails too
// if (!requestOptions)
// requestOptions = <RequestOptionsArgs> {
// withCredentials: true
// };
// else
// requestOptions.withCredentials = true;
return requestOptions;
}
}
// And this is how it's called
return this.http.get(this.config.urls.url("albums"))
.toPromise()
.then((response)=> {
this.albumList = response.json();
return this.albumList;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment