Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda