#How to return an observable boolean from an api call

1 messages · Page 1 of 1 (latest)

shy gorge
#

I'm trying to get some value in my component, after i make the call on my service
in my service i do :
getMyvar(key) {
return this.http.get<boolean>(URL/param).pipe(res=> of(res))

in my component i'm trying
getApi(key) {
this.result = this.myVar
.getMyvar(key)
.subscribe((valid) => (this.MyVar = valid))

but i'm getting an object like { isScalar = false ... etcv)

charred wren
#

just remove .pipe(res=> of(res) you don't need that and it doesn't make sense

shy gorge
#

Oh, and after the call how can i retrieve the result? with a map

fierce cosmosBOT
upbeat vapor
#

rxjs/operators go inside of .pipe(), not raw arrow functions.

charred wren
#

.subscribe(valid => {console.log(valid)}) what do you see here? it might already be a boolean otherwise you can use .map()

supple valley
#
this.http.get<boolean>(URL/param).pipe(res=> of(res))

I assume your response is not boolean, the generic type on get() is not your EXPECTED result, but the response type. If you want to manipulate the response, use map operators

charred wren
#
return this.http.get<boolean>(URL/param).pipe(
   map(res => {
    console.log(res);
    return res.isValid; // I don't know what res is, this is an example
   });
);
shy gorge
#

@charred wren Thank you very much!

#

I got it!

dapper sapphire
charred wren
dapper sapphire
#

Yes, I understand that. That's why the generic type of get() should be { isValid: boolean; } and not boolean.

charred wren
#

ohh I got what you mean, true!

shy gorge
charred wren
#

what do you see in your console.log ?

shy gorge
#

in the console log i got true

#

but i'm trying to do like instead of console log, i'm trign to put my const = valid

#

but the const turns out undefined

charred wren
#

then you can do it as you did before:
.subscribe(valid=> this.myVar = valid)

charred wren
#

please share the code

shy gorge
#

ok one moment

#
getCampanhaInfoApi(chaveUsuario: string) {
    this.result = this.npsDataService
      .getNpsValidation(chaveUsuario)
      .subscribe((validation) => (this.isNPSValid = validation));

    console.log('log no getCampanhaInfoApi', this.isNPSValid);
    return this.isNPSValid;
  }
}
charred wren
#

the problem is that when you do an HTTP request it takes some time. Generally Observables run asynchronously this means when you do console.log('log no getCampanhaInfoApi', this.isNPSValid); the HTTP request is still ongoing and not completed yet.

dapper sapphire
# shy gorge ``` getCampanhaInfoApi(chaveUsuario: string) { this.result = this.npsDataSer...

You're not understanding asynchrony. Read the comments in the code:

getCampanhaInfoApi(chaveUsuario: string) {
    this.result = this.npsDataService
      .getNpsValidation(chaveUsuario) // this is executed at t0
      .subscribe((validation) => 
        (this.isNPSValid = validation) // this is executed at t45678765, looooong after the method has returned and the console log has been executed, when the response finally arrives from the server.
      );

    console.log('log no getCampanhaInfoApi', this.isNPSValid); // this is executed at t1
    return this.isNPSValid;
  }
}
shy gorge
charred wren
#

what you should do is this:

getCampanhaInfoApi(chaveUsuario: string):Observable<boolean> {
    return this.npsDataService
      .getNpsValidation(chaveUsuario).pipe(
        tap(isValid => {
            console.log('isValid', isValid);
            this.isNPSValid = isValid; // honestly I don't know if you need this, why do you want to store it in this.isNPSValid ?
        })
      );
  }
shy gorge
#

should i put some async

dapper sapphire
#

You should return an observable from your method. Not a boolean. You can't return a synchronous result if it'sb obtained asynchrnously.

charred wren
#

then you can do getCampanhaInfoApi("myKey").subscribe(isValid => console.log('second log'. isValid))

shy gorge
shy gorge
#

the way @charred wren said works, but when i try to get the console lof od isNpsValid , it got undefined

dapper sapphire
#

Have you read and understood this? #1030086751714283602 message

#
someAsynchronousObservable.subscribe(event => {
  this.foo = event;
  // here, this.foo is defined
});
// here, this.foo is undefined, because when this part of the code is executed, the function passed to subscribe hasn't been executed yet.

Asynchrony is like sending an email: you can't expect to be able to read the response to an email immediately after you've sent the email. You can only do that when the email client has notified you that the response is available.

shy gorge
upbeat vapor
#
interface ViewModel {
  isNPSValid: boolean;
}

@Component({
  template: `
<pre *ngIf="vm$ | async as vm; else loading">For Debugging: {{ vm | json }}</pre>
<ng-template #loading>Loading...</ng-template>
`,
})
export class TheComponent {
  public readonly vm$: Observable<ViewModel>;

  constructor(private readonly npsDataService: NpsDataService) {
    this.vm$ = this.getCampanhaInfoApi('some string').pipe(
      map((isNPSValid: boolean): ViewModel => ({ isNPSValid })),
    );
  }

  private getCampanhaInfoApi(chaveUsuario: string): Observable<boolean> {
    return this.npsDataService.getNpsValidation(chaveUsuario);
  }
}

Using the AsyncPipe (| async in your template). And the View Model pattern.

#

Not knowing where chaveUsuario comes from makes it hard to suggest specifically what you do.

shy gorge
#

chaveusuario trasnlated is like userkey

upbeat vapor
#
interface ViewModel {
  isNPSValid: boolean;
}

@Component({
  template: `
<pre *ngIf="vm$ | async as vm; else loading">For Debugging: {{ vm | json }}</pre>
<ng-template #loading>Loading...</ng-template>
`,
})
export class TheComponent {
  public readonly vm$: Observable<ViewModel>;

  constructor(
    private readonly npsDataService: NpsDataService,
    private readonly storageService: StorageService,
  ) {
    this.vm$ = this.storageService.get('userkey').pipe(
      switchMap((chaveUsuario: string): Observable<booleam> => this.npsDataService.getNpsValidation(chaveUsuario)),
      map((isNPSValid: boolean): ViewModel => ({ isNPSValid })),
    );
  }
}