Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
Angular 2 - get json file names from http.get

In a server directory I have a list of json files. I need to import each json filename into my angular 2 component in an array of string or other structure.

I tried to make an http.get to the web server using this service.

export class AnUtenteService {
   getFiles() : Observable<string[]> {
      return this.http.get(directory)
         .map(this.extractData)
         .catch(this.handleError);
   }

   private extractData(res: Response) {
      let body = res.json();
      return body.data || { };
   }
   private handleError (error: any) {
   let errMsg = (error.message) ? error.message :
   error.status ? `${error.status} - ${error.statusText}` : 'Server error';
   console.error(errMsg); // log to console instead
   return Observable.throw(errMsg);
  } 
}

But when in my component I call anutenteservice.getFiles() I get this error: Unexpected token < in JSON at position 0. This is my component

export class OrderslistComponent{
  newsList; 
  errorMessage;
  constructor(private anutenteservice: AnUtenteService,  private http: Http)
  {}
  ngOnInit() {
     this.anutenteservice.getFiles()
     .subscribe(data => this.newsList = data,
                error => this.errorMessage = <any>error);
  }

}

I don't understand where is the mistake. What should I do?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Try to do this structure:

export class OrderslistComponent {
    newsList;
    errorMessage;

    constructor(private anutenteservice: AnUtenteService) {
        this.anutenteservice.getFiles.subscribe((data) => {
                this.newsList = data;
            }
        );
    }

    ngOnInit() {
    }    
}

And add Http to your service class. Add this to your service class:

constructor(private http: Http) {
}

Update 1:

Try changing the type, here:

  private extractData(res: Response) {
      let body = res.text();
      return body.data || { };
   }

In case your response type is not a JSON.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!