简体   繁体   中英

RxJS map return data before a subscription executed

In the code below the user return before code inside subscribe. Do you have any idea how to return user after subscription execution? Thanks for your help.

map(user => {
        console.log('!!user is::: ', !!user);
        this.httpService.makePostRequest('login', {}, true).subscribe((response: any ) => {
          if (!response.success) {
            return null;
          } else {
            user.token = response.token;
            this.globals.params.user.token = response.token;
            console.log(user.token);
          }
        });
        return !!user;
      })

first thing first, don't subscribe in an observable. Your user is returned first because your subscribe function takes time to respond (it's an asynchronous operation). If you want to execute your post request before returning your user, you can do something like this:

mergeMap(user => {
    console.log('!!user is::: ', !!user);
    return this.httpService.makePostRequest('login', {}, true).pipe(
        map((response: any ) => {
            if (!response.success) {
                return null;
            } else {
                user.token = response.token;
                this.globals.params.user.token = response.token;
                console.log(user.token);
            }
            return user;
        })
    );
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM