Skip to content

Instantly share code, notes, and snippets.

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 JhonBv/397508d4ccf943be478d15bc818533eb to your computer and use it in GitHub Desktop.
Save JhonBv/397508d4ccf943be478d15bc818533eb to your computer and use it in GitHub Desktop.
Angular HttpClient (5)
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
/** This class implements some features that should be tested. */
@Injectable()
export class HttpClientFeatureService {
constructor(
private http: HttpClient
) {}
login(user: string, password: string): Observable<boolean> {
const body = new HttpParams()
.set(`user`, user)
.set(`password`, password);
const headers = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });
return this.http.post(`auth/login`, body.toString(), { headers, observe: 'response' })
.map((res: HttpResponse<Object>) => res.ok)
.catch((err: any) => Observable.of(false));
}
}
@JhonBv
Copy link
Author

JhonBv commented Jul 5, 2018

There is an easier way though!

let body = new URLSearchParams();
body.set('username', this.username);
body.set('password', this.password);
body.set('grant_type', gtype);
body.set('client_id', clid);
body.set('client_secret', secid);
URLSearchParams() will automatically encode all of the body content in application/x-www-form-urlencoded

then:
return this.http.post(this.apiRoot, body).subscribe(result =>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment