最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular - return boolean from function with subscribe block - Stack Overflow

programmeradmin3浏览0评论

Trying to return a boolean value from below function in Angular Service but its not working please help !

isActive(id: string): boolean {
        if (!id) {
            return false;
        }
        let userActive = false;
        this.getUsers().subscribe(ActiveUsers => {
            const user = ActiveUsers.find(
                p => p.id === id
            );
            userActive = user ? true : false;
            return userActive;
        });
    }

async getUsers function (gets its users from an API) :

getUsers(): Observable<user[]> {
        
}

Trying to return a boolean value from below function in Angular Service but its not working please help !

isActive(id: string): boolean {
        if (!id) {
            return false;
        }
        let userActive = false;
        this.getUsers().subscribe(ActiveUsers => {
            const user = ActiveUsers.find(
                p => p.id === id
            );
            userActive = user ? true : false;
            return userActive;
        });
    }

async getUsers function (gets its users from an API) :

getUsers(): Observable<user[]> {
        
}
Share Improve this question edited Sep 16, 2020 at 23:32 FE_Addict asked Sep 16, 2020 at 23:13 FE_AddictFE_Addict 6774 gold badges11 silver badges22 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

I would remend to create a variable in your ponent and store the value there. Then you can use it whenever you need it. I dont know if getUsers is async, so keep that in mind.

isActive(id: string): boolean {
        if (!id) {
            this.isActiveValue = false;
        }
        let userActive = false;
        this.getUsers().subscribe(ActiveUsers => {
            const user = ActiveUsers.find(
                p => p.id === id
            );
            userActive = user ? true : false;
            this.isActiveValue = userActive;
        });
    }

EDIT: Ok, then you should keep something in mind. If you have a method that has an observable, then it should return another observable or nothing, just to keep things consistent. Try this:

isActive(id: string): Observable<boolean> {
        var subject = new Subject<boolean>();        
        let userActive: boolean = false;
        this.getUsers().subscribe(ActiveUsers => {
            const user = ActiveUsers.find(
                p => p.id === id
            );
            userActive = user ? true : false;
            subject.next(userActive);
        });
        return subject.asObservable();
    }

Usage:

isActive(id).subscribe(result => console.log(result));

Because this is invoking an observable (which is asynchronous), you would need to return an observable or a promise.

Returning an observable:

isActive(id: string): Observable<boolean> {
    return this.getUsers()
        .pipe(
            map(
                activeUsers =>
                    !!(activeUsers.find(p => p.id == id))
            )
        );
    }

Usage:

isActive(id).subscribe(result => console.log(result))

If I wanted a promise, I would start with this code and add some more:

isActive(id: string): Promise<boolean> {

    const isActiveObservable = this.getUsers()
        .pipe(
            map(
                activeUsers =>
                    !!(activeUsers.find(p => p.id == id))
            )
        );
    };
    return new Promise<boolean>(
        (resolve, reject) {
            let subscription = isActiveObservable 
                .subscribe({
                    next: isActive => {
                        subscription.unsubscribe();
                        resolve(isActive);
                    },
                    error: e => reject(e) 
                }
            );
        } 
    );
}

Usage:

isActive(id).then(userIsActive => console.log(userIsActive));

Or using the async keyword:

let userIsActive:boolean = await isActive(id);
console.log(userIsActive)
发布评论

评论列表(0)

  1. 暂无评论