Created
March 20, 2019 14:25
-
-
Save CharlesAMoss/34e594bf948ac027949e48c77cf19f79 to your computer and use it in GitHub Desktop.
httpclient angular
This file contains 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
rest.service.ts | |
import { Injectable } from '@angular/core'; | |
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class RestService { | |
XKCD_URL = 'https://xkcd.com'; | |
constructor(private httpClient: HttpClient) { } | |
getCurrentXKCD() { | |
return this.httpClient.get(`${this.XKCD_URL}/info.0.json`); | |
} | |
} | |
comic.component.ts | |
import { Component, OnInit } from '@angular/core'; | |
import { RestService } from '../rest.service'; | |
@Component({ | |
selector: 'app-comic', | |
templateUrl: './comic.component.html', | |
styleUrls: ['./comic.component.css'] | |
}) | |
export class ComicComponent implements OnInit { | |
private comic = []; | |
constructor(private restService: RestService) { } | |
ngOnInit() { | |
this.getCurrentXKCD(); | |
} | |
public getCurrentXKCD() { | |
this.restService.getCurrentXKCD().subscribe((data: any[]) => { | |
this.comic = data; | |
console.log(this.comic); | |
}); | |
} | |
} | |
// don't forget the modules | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment