The issue of returning a boolean value in an rxjs function leading to failure

Hey there, I am currently learning about rxjs and I want to create an observable that returns either true or false.

This is my attempted code:

checkLoggedIn(): Observable<boolean> {
  // Check with the server if the user is logged in
  if(this._tokenService.getToken()){ 
    // This function returns synchronous true or false

      this._httpservice.checkIfLoggedIn()
         .subscribe((res) => {
            return res.data; // This value will be true or false
              },
              err => { return false; }
              )    
     } else {
        return new Observable(observer => {
          observer.next(false);
          observer.complete();
        });
    }

 }

How can I modify the 'else' part above to ensure it works with the boolean observable so that in other components I can simply do:

this._authservice.checkLoggedIn()
  .subscribe(res => console.log(res));

Answer №1

everything seems to be functioning properly

verifyUserSession():Observable<boolean> { 
  if(this._tokenService.getToken()){ 
    return this._httpservice.checkSessionStatus().map(res=>res.success ) ;
  } else { 
    return Observable.of(false);
  }
}

Answer №2

Opt for return Observable.of(false) over using return false.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason behind the smaller bundle size of Angular2 CLI with "--prod" compared to "--prod --aot"?

Using the latest angular-cli (beta-18) for my project has brought an interesting observation to light. Despite being in its early stages, I am puzzled by the fact that my final bundle size is actually smaller without ahead-of-time (AoT) compilation. Upon ...

Moving the marker does not update the address

When the dragend event is triggered, the Getaddress function will be called in the following code: Getaddress(LastLat, LastLng , marker,source){ this.http.get('https://maps.googleapis.com/maps/api/geocode/json?latlng='+LastLat+ &apos ...

Avoid stopping Bootstrap Vue's events

Need help with a b-form-select control in Bootstrap Vue. Trying to execute a function when the value changes, but want the option to cancel the event and keep the original value. Complicating matters, the select is in a child component while the function ...

Excluding node modules when not included in tsconfig

Within my Angular project, there is a single tsconfig file that stands alone without extending any other tsconfigs or including any additional properties. Towards the end of the file, we have the following snippet: "angularCompilerOptions": { ...

Obtaining the created by and modified by values from a SharePoint list can be achieved using Angular's http get method

I have received a response that includes the Created date and Modified date, but the Created by and Modified by information is missing. this.http.get(this.baseurl + "_api/web/lists/getByTitle('mylist')/items?$select ID,Created,CreatedBy, ...

Creating a custom Typescript type by leveraging Javascript variables as the key identifiers

Picture a Typescript library that serves as a database interface, giving developers the ability to specify record attributes/columns/keys to be retrieved from the database. Is it feasible to return a type that includes the keys specified by the developer? ...

Fetching data from an API using Observables in Angular

I am facing a challenge with an API endpoint that returns an array of strings in JSON format. My goal is to display these contents on a webpage using an Angular Service. Below is the code snippet I have implemented so far (working with Angular 7): export ...

What is the proper method for specifying the path to my index.tsx file within a React application?

After using npx create-react-app my-app --template typescript to generate my React app, I decided to reorganize the files by moving them to /src/client and relocating my Express backend to /src/server. However, upon running the relocated React app, I encou ...

Is there a way to insert data from one table into a MySQL Table in Drizzle and update the entry if it already exists?

My goal is to utilize Drizzle for inserting data into a table and updating it if the key already exists. In MySQL, the code would look like this: INSERT INTO myTable1(field1,field2,field3,field4) SELECT fieldOne,fieldTwo,fieldThree,fieldFour FROM myTable2 ...

Passing a username and password to an API in Angular 6: Step-by-step guide

Can someone assist me with this problem? I am struggling to pass the username and password in my API request for a list of homes. Every attempt I've made has resulted in an unauthorized access error. How do I correctly include the user credentials (pe ...

Leveraging the Power of JavaScript within Angular 12

Currently, I am in the process of learning how to utilize Angular 12 and am attempting to create a sidenav. While I am aware that I can use angular material for this task, I would prefer not to incorporate the associated CSS. My goal is to integrate this ...

Angular template in PhpStorm displaying error: Unresolved pipe issue

I am currently working on a project generated by Angular CLI version 7.3.9 (Angular version 7.2.0) and using IDE: PhpStorm version 2019.1.2. Within the template of my component, I am utilizing the UpperCasePipe: <h2>{{ title | uppercase }}</h2&g ...

Unable to invoke Angular function from within jQuery

I am currently using the angular full calendar plugin and have successfully added a context menu in the event render function. The context menu is functioning properly, but I am facing an issue where I want to call an Angular function when a context menu i ...

What is the best way to store the output of a function in a local variable?

In my Type Script code, I am looking to store the return value of a function in a local variable. The process is outlined below: getdetail1(store){ let Cust_id=this.sharedata.latus_lead.m_type let url="http:domain.com" console.lo ...

Using static methods within a static class to achieve method overloading in Typescript

I have a TypeScript static class that converts key-value pairs to strings. The values can be boolean, number, or string, but I want them all to end up as strings with specific implementations. [{ key: "key1", value: false }, { key: "key2&qu ...

Resetting FormArray upon selecting a new value from a dropdown in Angular 4 Reactive Forms

I am facing an issue where I need to choose a warehouse before being able to view the ingredients. The problem arises when attempting to switch warehouses, as I need to clear the form array or the entire form since each warehouse has a different set of i ...

Error message encountered: Missing property status in TypeScript code

An error occurs in the refetchInterval when accessing data.status, with a message saying "property status does not exist" chatwrapper.tsx const ChatWrapper = ({ fileId }: ChatWrapperProps) => { const { data, isLoading } = trpc.getFileUploadStatus.use ...

"What is the best way to add content to the end of the last child element using Angular's

Currently, I am facing an issue with appending a button after an input field using an Angular7 directive. The problem lies in the fact that the Renderer2 method appendChild is placing the button before the input field. Button appearing before the input fi ...

What is the best way to change an existing boolean value in Prisma using MongoDB?

Exploring prisma with mongoDb for the first time and faced a challenge. I need to update a boolean value in a collection but struggling to find the right query to switch it between true and false... :( const updateUser = await prisma.user.update({ where: ...

Sporadic UnhandledPromiseRejectionWarning surfacing while utilizing sinon

Upon inspection, it appears that the objects failApiClient and explicitFailApiClient should be of the same type. When logging them, they seem to have identical outputs: console.log(failApiClient) // { getObjects: [Function: getObjects] } console.log(expli ...