Include module first
"app/app.module.ts (excerpt)"
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
Now start to use in your component
" app/config/config.service.ts (excerpt)"
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
export interface Config {
heroesUrl: string;
textfile: string;
}
@Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
getPosts() {
return this.httpClient.get('https://run.mocky.io/v3/fa3dc43e-6320-4202-b5b5-dba520d00014')
.subscribe((data: Config) => this.config = {
heroesUrl: data['heroesUrl'],
textfile: data['textfile']
});
}
this.getPosts();
console.log(this.config);
}
PS.
-
Define response data by `interface Config`
-
If the url lost, you could make one on https://run.mocky.io
-
Use `.subscribe` to get the response data. <– important
Leave a Reply