-1

I have this method and I would like to return true/false from it, but I am getting this error: A function whose declared type is neither 'void' nor 'any' must return a value.

  public isLoggedIn(): boolean {
    const url = `${this.endPoint}/me`;
    this.http.get<any>(url).subscribe(
      () => {
        return true;
      },
      () => {
        return false;
      }
    );
  }
IAfanasov
  • 4,775
  • 3
  • 27
  • 42
AzafoCossa
  • 874
  • 8
  • 18

3 Answers3

1

That is quite a misunderstanding of Observables and TypeScript here.

You can save the value returned from the observable to a property

  public isLoggedIn: boolean;
  public loadIsLoggedIn(): boolean {
    const url = `${this.endPoint}/me`;
    this.http.get<any>(url).subscribe(
      () => {
        this.isLoggedIn = true;
      },
      () => {
        this.isLoggedIn = false;
      }
    );
  }

Another option is to use a promise

  public async loadIsLoggedIn(): Promise<boolean> {
    const url = `${this.endPoint}/me`;
    try {
       return await this.http.get<any>(url);
    } catch {
       return false
    }
  }

async pipe usually is the best option. The provided code is not enough to provide a sample for your case. I would you can manage to figure out its usage.

IAfanasov
  • 4,775
  • 3
  • 27
  • 42
  • 3
    This is a known issue with a known duplicate that's been used thousands of times. Please refrain from answering duplicates like these. – Heretic Monkey Aug 23 '21 at 16:32
1

You can change the logic in your method to return an Observable

 public isLoggedIn(): Observable<boolean> {
    const url = `${this.endPoint}/me`;
    return this.http.get<any>(url)
      .pipe(
        // map operator is called when the HTTP call is successful
        map(() => true),
        // catchError operator is called when the HTTP call encounters an error
        catchError((error) => of(false))
      );
  }

And you can subscribe to it where you need the boolean value

sp814610
  • 36
  • 6
0

You can work with what you get from Observable like this:

public isLoggedIn: boolean;

...

this.httpService.isLoggedIn()
 .subscribe(
   (result) => {
     this.isLoggedIn = true;
   },
   (error) => {
     this.isLoggedIn = false;
   }
);
isLoggedIn(): Observable<boolean> {   
  const url = `${this.endPoint}/me`;
  return this.http.get<any>(url);
}
Salahuddin Ahmed
  • 4,854
  • 4
  • 14
  • 35