Make an http request by Angular

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.

  1. Define response data by `interface Config`

  2. If the url lost, you could make one on https://run.mocky.io

  3. Use `.subscribe` to get the response data.   <– important

76 Comments

Leave a Reply

Your email address will not be published.