1

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

5 Answers 5

3

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
        })
    }

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

1 Comment

Would it not be better to type cast it at observable level as an array of items? For example... this.http.get<Book[]>(url).subscribe(books => { books.forEach((book, index) => { console.log("Book: " + JSON.stringify(book ) + " : at index: " + index); }); }, error => console.log('Could not load book.'));
2

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>

3 Comments

you have to use this keyword to access them inside functions this.my_class_variable_example
you have to add the this keyword to your forEach as I have explained.
i didn't notice he had another class books, however, the books in the observables is not the same as the class. therefore no this added to that.
0

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>

6 Comments

I can't declare 'arrayofObj', I'm geting the following error Cannot find name 'arrayofObj'
You need to declare arrayofObj as a class variable (like you did for books and errorMessage). It should be arrayofObj: any[]; and then you access it with this.arrayofObj inside ngOnInit
Can you edit your question to show what you have now in your ts file and in your html ?
are you using forEach to iterate over books and then access arrayofObj ?
I don't understand your code, and some variables disappeared. What is retrivedata and newarray ? I am not sure if this is what you want to achieve, but you don't need to use a for loop inside your subscribe to get the books, you just assign it to a variable.
|
0

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);
                   });

6 Comments

yes, I tried, but getting ERROR TypeError: Cannot read property 'dispose' of null at AsyncPipe.webpackJsonp.../../../common/@angular/common.es5.js.AsyncPipe._dispose (common.es5.js:2761)
I used that in my own project.
<div *ngFor="let obj of arrayofObj"> <span>{{obj.fname}}</span> <span>{{obj.lname}}</span> </div> shall I use array of obj like this in html
for (let entry of books) { console.log(entry); // 1, "string", false try { users.insert({ username: entry.name }); } catch(error) { // console.log(error); } } console.log(users.get(1)); this.bookArr = db.getCollection('users').data || db.addCollection('users', { unique: ['username'] }).data;
please edit your code in the question. difficult to read in comment. you need to populate arrayofObj inside the subscribe depending on the values in this.books in order then to use it in the UI template. confirm if this is the case.
|
0
  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)
    }

  });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.