Error with map operator

Asked

Viewed 324 times

0

I’m starting now with Angular 6.

When I tried to create a service to consume data from an api, the following error appeared:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs';

import { CategoriaModel } from './categoria/categoria.model';
import { PRODUTOS_API } from './../../app.api';

@Injectable()
export class CategoriasService{
constructor(private http: Http){}

categorias(): Observable<CategoriaModel[]>{
    return this.http.get(`${PRODUTOS_API}/categorias`).map(response => response.json())
}

}

Error: Property 'map' does not exist on type 'Observable'.

I wonder what I’m doing wrong?

  • 1

    please post the code instead of images. https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-fazer-perguntas/5485#5485

3 answers

0

you need to import the MAP operator

    import { map } from "rxjs/operators";

    categorias(): Observable<CategoriaModel[]>{
        return this.http.get(`${PRODUTOS_API}/categorias`)
        .pipe(map(response => response.json()));
    }

0

If you use the Httpclient library instead of http you don’t need to map to json. Another thing tbm, vc can use the Generics and pass its Interface that the angular automatically infers the type of return of your Observable.

constructor(private httpClient: HttpClient){}

categorias(){
    return this.httpClient.get<CategoriaModel[]>(`${PRODUTOS_API}/categorias`)
   }
}
  • The service presented no more errors. Agora, o Console do browser informou o seguinte:&#xA;&#xA;ERROR Error: StaticInjectorError(AppModule)[CategoriasService -> HttpClient]: &#xA; StaticInjectorError(Platform: core)[CategoriasService -> HttpClient]: &#xA; NullInjectorError: No provider for HttpClient!

  • Import Httpclientmodule where you had imported Httpmodule

  • It is one mistake after another. Discouragement saw...

  • My ng-for cannot iterate with my Komponent return. says ng-for is trying to iterate with [Object Object]. How I turn the return of the service into an array?

0

I managed to solve Eduardo Varga. Thanks for the guidelines.

The Component that receives the Injection should look like this:

ngOnInit() {
this.categoriasService.categorias().subscribe(categorias => this.categorias = categorias)

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.