简体   繁体   中英

how to fetch data from service in angular 6?

I am using this api's for my demo app ( https://restcountries.eu/ )

API url is this https://restcountries.eu/rest/v2/all

But I am not able to fetch data from service in angular

here is my code https://stackblitz.com/edit/angular-3jpqrc?file=src%2Fapp%2Fapp.component.ts

constructor(private dataservice : DataService){

     this.dataservice.fetchDataThroughPromise().subscribe(()=>{
      console.log('s')
    })
  } 

service code

 fetchDataThroughPromise(){
    return this.http.get('https://restcountries.eu/rest/v2/all',
      {
        headers :new HttpHeaders({
          'content-type': 'application/json'
        })
      });
  }

see error when created project using angular cli

在此处输入图片说明

Just remove:

    headers :new HttpHeaders({
      'content-type': 'application/json'
    })

Final code:

fetchDataThroughPromise() {
  return this.http.get('https://restcountries.eu/rest/v2/all')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM