alex
alex

Reputation: 414

How to transfer a subscription to another function

I have a UserService function, I subscribe to it. If there are no errors, I take the data and want to return it with the possibility of another function to subscribe to it. I already had a similar question, but there were two nested functions, there the issue was solved using switchMap. But how can it be used here? so that you can write like this:

this.authService.getUser(1).subscribe(...

But this code gives an error, I myself understand that this is wrong, but I don't understand how to use switchMap or map here:

export class AuthService {
getUser(id: number): Observable<User | null> {  
  this.httpService.getUser(id).subscribe(
    (resultService: DataResponse<User>) => {
      if (resultService.status === StatusType.SUCCESSFUL) {
        return resultService.data;
      } else {
        return null;
      }
    });
}
}
    
export interface User{
  id: number;
  name: string;
}  

Upvotes: 1

Views: 866

Answers (2)

Amer
Amer

Reputation: 6706

To achieve that you have to return the Observable itself from the getUser function, instead of subscribe within it.

You can try something like the following:

// import {map} from 'rxjs/operators';

getUser(id: number): Observable<User | null> {
  return this.httpService.getUser(id).pipe(
    map((resultService: DataResponse<User>) => {
      if (resultService.status === StatusType.SUCCESSFUL) {
        return resultService.data;
      } else {
        return null;
      }
    })
  );
}

The map operator is used here to transform the result of the this.httpService.getUser to the preferred type.

Then you can subscribe to it within the other components when you need it only:

this.authService.getUser(1).subscribe(...)

Upvotes: 3

Zerotwelve
Zerotwelve

Reputation: 2361

you should avoid to subscribe inside the function, you should return the observable instead in order to subscribe to the function:

export class AuthService {
  getUser(id: number): Observable<User | null> {  
    return this.httpService.getUser(id).pipe(
      map((resultService: DataResponse<User>) => {
        if (resultService.status === StatusType.SUCCESSFUL) {
          return resultService.data;
        } else {
          return null;
        }
      })
    );
  }
}

and if you want you can make you code much shorter:

getUser(id: number): Observable<User | null> {  
  return this.httpService.getUser(id).pipe(
    map((res: DataResponse<User>) => res.status === StatusType.SUCCESSFUL ? res.data : null)
  );
}

Upvotes: 3

Related Questions