creating class as Iterable in angular/typescript

Viewed 2952

I have created a class in angular, now when I fetch an object via store subscription, although it returns an array of object, but I cannot use forEach loop on the returned object.

Yes, I have used Object.keys(user).forEach(){..} It is working, but I want to do the same thing by making class Iterable. How To this.

Sample code:-

class user {
    ...
}
ngOnInit(){
    storeSubsc = this.store.select('users').subscribe(user => {
        this.user = user;
    });
}

login(){
    Object.keys(this.user).forEach()... --> working fine
    I want it like
    this.user.forEach() {... }
}

Thanks in Advance...

2 Answers

In order for your class to be iterable, your class needs to have a method of Symbol.iterator:

class User implements Iterable<string> {
    // ...
    constructor(private username: string, private password: string) { }

    *[Symbol.iterator](): Iterator<string> {
        for (let key of Object.keys(this)) {
            yield key;
        }
    }
}

const u = new User('blabla', '1234');
for (let k of u) {
    console.log(k);
}

In this case I used a generator function.

You can use for in operator:

class User {
  // 
}

const user = new User(/*args*/); 
for (let prop in user) {
  console.log(prop, user[prop]);
}

Additionally, you can check if the class instance has the prop as its own property user.hasOwnProperty(prop) inside the for in loop. For example, if your User class extends another base class and without checking hasOwnProperty you will see the constructor as well:

class BaseUser {
  constructor(public x, public y) { }
}

class User extends BaseUser {
  constructor(public a, public b, public x, public y) {
    super(x, y);
  }
}

const user = new User('12', 2, 111, 222); 
for (let prop in user) {
  alert(prop);
}

You will see five alerts: x, y, a, b, constructor.

Related