Skip to content

Instantly share code, notes, and snippets.

@PyroGenesis
Last active May 19, 2019 11:10
Show Gist options
  • Save PyroGenesis/5079654130153b407223fca228f08443 to your computer and use it in GitHub Desktop.
Save PyroGenesis/5079654130153b407223fca228f08443 to your computer and use it in GitHub Desktop.
The simplest requests (GET and POST)
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
// Injectable indicates a dependency injectable service
// providedIn indicates the level at which components can access it
@Injectable({
providedIn: 'root'
})
export class SimpleRequestService {
// We use HttpCLient to perform the requests
constructor(private httpClient: HttpClient) { }
// Simple GET request
simpleGET(): Observable<any> {
const URL = 'YOUR_URL_HERE';
return this.httpClient.get(URL); // returns an Observable
}
// Simple POST request
simplePOST(): Observable<any> {
const URL = 'YOUR_URL_HERE';
const data = null;
return this.httpClient.post<any>(URL, data); // returns an Observable
}
}
import { Component, OnInit } from '@angular/core';
import { UtilityService } from 'src/app/services/utility.service';
@Component({
selector: 'app-simple-page',
templateUrl: './simple-page.component.html',
styleUrls: ['./simple-page.component.css']
})
export class SimplePageComponent implements OnInit {
// Injecting the request service
constructor(private simpleRequestService: SimpleRequestService) { }
ngOnInit() {
// Subscribing to simple GET (Similar for POST
this.simpleRequestService.simpleGET().subscribe(
getResp => {
console.log('data from simple GET', getResp);
}, getError => {
console.log('error from simple GET', getError);
}, () => {
console.log('GET complete');
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment