This is a good reference, it helped me switch my http
requests to httpClient
.
It compares the two in terms of differences and gives code examples.
This is just a few differences I dealt with while changing services to httpclient in my project (borrowing from the article I mentioned) :
import {HttpModule} from '@angular/http';
import {HttpClientModule} from '@angular/common/http';
this.http.get(url)
// Extract the data in HTTP Response (parsing)
.map((response: Response) => response.json() as GithubUser)
.subscribe((data: GithubUser) => {
// Display the result
console.log('TJ user data', data);
});
this.http.get(url)
.subscribe((data: GithubUser) => {
// Data extraction from the HTTP response is already done
// Display the result
console.log('TJ user data', data);
});
Note: You no longer have to extract the returned data explicitly; by default, if the data you get back is type of JSON, then you don't have to do anything extra.
But, if you need to parse any other type of response like text or blob, then make sure you add the responseType
in the request. Like so:
responseType
option: this.http.get(url, {responseType: 'blob'})
.subscribe((data) => {
// Data extraction from the HTTP response is already done
// Display the result
console.log('TJ user data', data);
});
I also used interceptors for adding the token for my authorization to every request, reference.
like so:
@Injectable()
export class MyFirstInterceptor implements HttpInterceptor {
constructor(private currentUserService: CurrentUserService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// get the token from a service
const token: string = this.currentUserService.token;
// add it if we have one
if (token) {
req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
}
// if this is a login-request the header is
// already set to x/www/formurl/encoded.
// so if we already have a content-type, do not
// set it, but if we don't have one, set it to
// default --> json
if (!req.headers.has('Content-Type')) {
req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
}
// setting the accept header
req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
return next.handle(req);
}
}
Its a pretty nice upgrade!