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

351
Visualizações
Angular 12 how to return an http get request array of objects and assign to other array of different type using map()

Hey I'm trying to implement a bootstrap5 dropdown following this example: Creating Multi-Select Dropdown with Angular and Bootstrap 5 In that example, to get the data, he uses an app.service and just returns an array of objects:

getFoods(): Food[] {
        return [
            {
                id: 1,
                name: 'Grapes'
            },
            {
                id: 2,
                name: 'Melon'
            },
...

And then in his ngOnInit() calls the getFoods() method and also uses .map() operator because he has to assign to values because the item model has two values:

ngOnInit(): void {
        this.items = this.appService.getFoods().map(fruit => ({
            id: fruit.id,
            name: fruit.name
        } as Item));
    }

So I'm trying to do hat but with data being fetched from an API endpoint using HTTP GET request. But I don't know how to use the .map() operator for the http get request:

this.subscription = this.contactSearchService.currentCodes.pipe(
            map(
                code => (
                    {
                        id: code.code,
                        name: code.code
                    }
                )
            )).subscribe(Response => {
                this.items = Response
            })

It's giving me these errors:

Property 'code' does not exist on type 'ResponsibilityCode[]'.
Type '{ id: any; name: any; }' is missing the following properties from type 'Item[]': length, pop, push, concat, and 26 more.

My http get request function:

private _reponsibilityCodeSource = new BehaviorSubject<ResponsibilityCode[]>([]);
currentCodes = this._reponsibilityCodeSource.asObservable();

getCodes(): void {
    this.http.get<ResponsibilityCode[]>('https://localhost:44316/api/SITEContacts/ResponsibilityCode').subscribe(Response => {
        this._reponsibilityCodeSource.next(Response);
      });
  }

I get the data as `JSON` btw.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The rxjs pipe(map(.... code...)) is different than array.map - pipe(map()) does not operate on each item of an array

So the errors you are getting is because you're swapping out the array of ResponsibilityCode for a single item (code in your code is all the responsibility codes)

Try

this.subscription = this.contactSearchService.currentCodes.subscribe(Response => {
                this.items = Response.map(
                code => (
                    {
                        id: code.code,
                        name: code.code
                    }
                )
            )
})
about 4 years ago · Juan Pablo Isaza Relatório

0

Your HTTP get returns an Observable of ResponsibilityCode array, so to achieve that you have to map (Array.prototype.map) the items of the array within the RxJS's map operator, like the following:

this.subscription = this.contactSearchService.currentCodes
  .pipe(
    map((res: ResponsibilityCode[]) =>
      res.map((item) => ({
        id: item.id,
        name: item.name,
      }))
    )
  )
  .subscribe((res) => {
    this.items = res;
  });
about 4 years ago · Juan Pablo Isaza 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