0

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>
9
  • {"id":4,"content":"Hello, World! "} this is not a list that's why you can not use it in ngFor Commented Jul 27, 2020 at 16:52
  • Can you send the exact response from API? Commented Jul 27, 2020 at 16:53
  • 2
    Assuming you have an array of objects of the form {id:.., content:..}, there is no name field in it Commented Jul 27, 2020 at 16:54
  • @AnuragSrivastava Even if you don't have name property it shouldn't give above error. So it looks like the response is not in array form. Commented Jul 27, 2020 at 16:56
  • I tried content and id, and both didn't work either. Commented Jul 27, 2020 at 16:56

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I didn't see that, that was exactly what it was. Once I did that, and changed to {{greeting.content}}, then it worked!
0

*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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.