Home > Net >  How to transfer a subscription to another function
How to transfer a subscription to another function

Time:02-17

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;
}  

CodePudding user response:

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)
  );
}

CodePudding user response:

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(...)
  • Related