baumli
baumli

Reputation: 471

Angular page is not displaying my array items

I'm trying to take a response and display the array on the page. There are no errors, but there also no list on the page.

My list is: {"id":4,"content":"Hello, World! "}

Here is my greeting-list.component.ts:

import { Component, OnInit } from '@angular/core';
import { GreetingService } from '../shared/greeting/greeting.service';
import { map } from "rxjs/operators"; 

@Component({
  selector: 'app-greeting-list',
  templateUrl: './greeting-list.component.html',
  styleUrls: ['./greeting-list.component.css']
})
export class GreetingListComponent implements OnInit {
  greetings: Array<any>;

  constructor(private greetingService: GreetingService) { }

  ngOnInit(): void {
    //this.greetingService.getAll().subscribe(data => {
    //  this.greetings = data;
    //});
    this.greetingService.getAll().pipe(map(data => {
      this.greetings = [data];
    }));

  }

}

I originally had:

    //this.greetingService.getAll().subscribe(data => {
    //  this.greetings = data;
    //});

but I was getting an error Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object' so I changed it to the code below it.

Here is my greeting-list.component.html:

<div *ngFor="let greeting of greetings">
  {{greeting.name}}
</div>

Upvotes: 0

Views: 135

Answers (2)

Clint
Clint

Reputation: 1073

*ngFor will only work with arrays (not objects or anything else)

if you are trying too iterate over an object use object.keys(yourbobject) *ngFor = "let greetingKey of Object.keys(greetings)"

<div *ngFor="let greeting of greetings">
  {{greeting[greetingKey].name}}
</div>

you will also need to add public object = Object; in your Component TS file

Upvotes: 0

Tsvetan Ganev
Tsvetan Ganev

Reputation: 8856

You have to subscribe to the observable:

 this.greetingService.getAll().pipe(map(data => {
   this.greetings = [data];
 })).subscribe();

Without subscribing the observable will never emit a value.

Upvotes: 1

Related Questions