Honey
Honey

Reputation: 386

Iterate Array of object in Angular 4

I want to interate array object inside the subscribe

test.ts file

  export class AppComponent  implements OnInit {
      title = 'app works!';
      observableBooks: Observable<Book[]>
      books: Book[];
      newarray: any[];
      errorMessage: String;
      constructor(private bookService: BookService) { }
      ngOnInit(): void {
           this.observableBooks = this.bookService.getBooksWithObservable();
               this.observableBooks.subscribe(books => { 
             for (let entry of books) {
               // push the value into db
          }

         let retrivedata: Array<number> = //retrive the db collection again




                error =>  this.errorMessage = <any>error
              });

      }

    }

test.html file

<ul *ngFor="let book of retrivedata | async">
      <li>{{book.price}}</li>
    </ul>

I need to iterate this "arrayofObj" in HTML page, which means angular template page

Upvotes: 1

Views: 48320

Answers (5)

Amir Touitou
Amir Touitou

Reputation: 3441

  this.service.getDevicesByJson().subscribe(data => 
  {
    this.devicesJson = data;

    objArray = JSON.parse(this.devicesJson.toString());

    for(let obj of  objArray)
    {
      let info = new DeviceInfo();
      info.Address = obj["deviceAddress"]
      info.Name = obj["deviceName"]

      this.devices2.push(info)
    }

  });

Upvotes: 0

HDJEMAI
HDJEMAI

Reputation: 9800

If you want to iterate an array, but you are inside the subscribe, and if you are using forEach, you need then to add the this parameter for forEach to access the outside scope.

Example:

this.observableBooks.subscribe(
   (books) =>  {
                   this.books = books;

                   //iterate over arrayofObj
                   books.forEach( (book) => {
                                              //this will work 
                                              this.arrayofObj.push({fname: this.book.name});
                                  }, this);
                   });

Upvotes: 0

Andy
Andy

Reputation: 1228

You have to declare a class variable to hold the information you are getting inside subscription 'books'.

You cannot use let retrivedata: Array<number> = //retrive the db collection again on your view. You need to declare this variable in a class level. Take a look:

 export class AppComponent  implements OnInit {
  title = 'app works!';

  retrivedata: Array<object> = []; // your view variable has to be created in a class level

  observableBooks: Observable<Book[]>
  books: Book[];
  newarray: any[];
  errorMessage: String;

  constructor(private bookService: BookService) { }

  ngOnInit(): void {

       this.bookService.getBooksWithObservable().subscribe(books => { 
         books.forEach(entry => {
           this.retrievedata.push(entry);  //assign the data from subscription to your class variable
         }
      }

 }

then in your view:

<ul *ngFor="let book of retrivedata"> // use your class variable in your view
  <li>{{book.price}}</li>
</ul>

Upvotes: 2

br.julien
br.julien

Reputation: 3460

Update :

I think if we make the code a bit cleaner, it should look close to this :

app.component.ts :

export class AppComponent implements OnInit {    
    books: Book[];
    errorMessage: string;
    constructor(private bookService: BookService) { }

    loadBooks() {
        this.bookService.getBooksWithObservable().subscribe(
            (res) => this.onSuccess(res.json),
            (res) => this.onError(res.json)
        );
    }

    ngOnInit() {
        this.loadBooks();
    }

    private onSuccess(data) {
        this.books = data;
    }
    private onError(error) {
        this.errorMessage = error.toString();
    }
}

HTML :

<div *ngFor="let book of books">
    <span>{{book.price}}</span>
</div>

Upvotes: 0

Chandru
Chandru

Reputation: 11184

Try like this :

export class AppComponent implements OnInit {

    private retrivedata: Array<any> = [];

    title = 'app works!';
    observableBooks: Observable<Book[]>
    books: Book[];
    newarray: any[];
    errorMessage: String;
    constructor(private bookService: BookService) { }
    ngOnInit(): void {
        this.observableBooks = this.bookService.getBooksWithObservable();
        this.observableBooks.subscribe(books => {
            console.log('books', books);
            this.retrivedata = books;
            for (let entry of this.retrivedata) {
                console.log('entry', entry)
            }
        }, (error) => {
            this.errorMessage = <any>error
        })
    }

}

Upvotes: 3

Related Questions