user630209
user630209

Reputation: 1207

Angular method not returns from if statement

This method never returns true. Eventhough it displays that true message in console. Why this behaviour ?

 purgeEmptyRows(obj: any) :Observable<boolean>  {
          let isEmpty = false;
          Object.keys(obj).forEach(key => {
          if( obj[key] != null) {
            if(typeof obj[key] != "object"){
            console.log("true");
              return Observable.of(true);
            }
          }else {
            isEmpty = false;
          }

          })
          return Observable.of(isEmpty);
    }

    }

Upvotes: 0

Views: 671

Answers (2)

frosty
frosty

Reputation: 21762

You're returning an Observable with the true inside of it. So you have two options.

First option, change the function to return a simple boolean instead of an Observable.

Second option, subscribe to the observable you are returning.

For the first option, do the following:

purgeEmptyRows(obj: any) :boolean  {
    let isEmpty = false;
    Object.keys(obj).forEach(key => {
        if( obj[key] != null) {
            if(typeof obj[key] != "object"){
                console.log("true");
                isEmpty = true;
            }
        } else {
            isEmpty = false;
        }

    });
    return isEmpty;
}

For the second option, you still need to change your code to be the following:

purgeEmptyRows(obj: any) : Observable<boolean>  {
    let isEmpty = false;
    Object.keys(obj).forEach(key => {
        if( obj[key] != null) {
            if(typeof obj[key] != "object"){
                console.log("true");
                isEmpty = true;
            }
        } else {
            isEmpty = false;
        }

    });
    return Observable.of(isEmpty);
}

And then, when you call the function, you will call subscribe to the result. Here is an example:

const obs = purgeEmptyRows(rows);
obs.subscribe(res => {
    console.log(res);
});

Upvotes: 1

vikvincer
vikvincer

Reputation: 649

I think the reason is you did not assign isEmpty inside.

if(typeof obj[key] != "object"){
   console.log("true");
  return Observable.of(true);
}

It should look like this

if(typeof obj[key] != "object"){
  isEmpty = true
}

Upvotes: 0

Related Questions