Last active
December 12, 2017 11:49
-
-
Save saiumesh535/2b17722159efb1d7e960bb6a2cd7bccb to your computer and use it in GitHub Desktop.
Angular 4/5 Http calls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // this is example to make http calls in angular 4/5 | |
| // not silver bullet to follow but it get's job done | |
| import { HttpClient,HttpHeaders,HttpParams } from '@angular/common/http'; | |
| export class SomeHttpService { | |
| constructor(private httpClient: HttpClient){} | |
| // simple get method | |
| this.httpClient.get<any>(URL); | |
| // get with some headers | |
| const headersObj = { | |
| 'Content-Type': 'application/x-www-form-urlencode', | |
| 'Authorization': `Bearer token}`}; | |
| const headers = new HttpHeaders(headersObj); | |
| this.httpClient.get<any>(URL,{headers: headers}); | |
| // get with headers and params | |
| const headersObj = { | |
| 'Content-Type': 'application/x-www-form-urlencode', | |
| 'Authorization': `Bearer token}`}; | |
| const headers = new HttpHeaders(headersObj); | |
| let params = new HttpParams(); | |
| params = params.append("key","value"); | |
| params = params.append("someotherKey","soeValue") | |
| this.httpClient.get<any>(URL,{headers: headers,params:params}) | |
| // simple post without headers | |
| this.httpClient.post(URL,{some: some}); | |
| // post with headers | |
| const headersObj = { | |
| "key":"someValue" | |
| } | |
| const headers = new HttpHeaders(headersObj); | |
| this.httpClient.post(URL,{some: some},{headers: headers}); | |
| // post with headers and form data for uploading files | |
| // NOTE: encType may vary based on library you are using for uploading files | |
| const headersObj = { | |
| 'encType': 'multipart/form-data', | |
| 'Authorization' : `Bearer token}` | |
| } | |
| const headers = new HttpHeaders(headersObj); | |
| const formData = new FormData(); | |
| formData.append("file1","file2"); // this is file | |
| formData.append("name","username"); // this is text | |
| this.httpClient.post<any>(URL,formData,{headers: headers}) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment