Retrieving a Boolean Value from HTTPClient

In my authorization service, I am working on verifying the existence of a user.

import { HttpClient } from "@angular/common/http";
import 'rxjs/Rx'

@Injectable()
export class AuthService {
    constructor( private http : HttpClient) {}

    registerUser(){
        var temp = doesUserExist().subscribe(x => temp = x);
        if(temp){
            //register User logic
        }
    }

    private doesUserExist(){
        var endpoint = [myPath];
        return this.http
            .get(endpoint)
            .map(payload => payload);
    }
}

When I send a GET request to [myPath], the server responds with:

[{"SqlResponse":"0"}]

I am facing issues with the map and subscribe functions. The code snippet above results in logging a Subscriber object. I tried different methods, like:

    private doesUserExist(){
        var endpoint = [myPath];
        return this.http
            .get(endpoint)
            .map(payload => payload.json());
    }

but encountered the error 'json() is not found on type 'Object'. I learned that .map already converts the string to JSON, so there is no need for this. I also attempted:

    private doesUserExist(){
        var endpoint = [myPath];
        return this.http
            .get(endpoint)
            .map(payload => payload[0]);
    }

which produced the same Subscription object in the console. I tried casting it as Observable<boolean>

    private doesUserExist() : Observable<boolean>{
        var endpoint = [myPath];
        return this.http
            .get<boolean>(endpoint)
            .map(payload => payload);
    }

but still ended up with a Subscriber object.

EDIT When I use this method...

var temp; doesUserExist().subscribe(x => {temp = x; console.log(temp); });

I still receive a generic object... How can I access that in TypeScript?

https://i.sstatic.net/CvOE7.png

Can anyone provide guidance on this issue? I believed mapping the result should work, but since I am getting an array of JSON as a response, it might be causing the problem.

Answer №1

Give it a shot

let userCheck: boolean;

private checkIfUserExists() : Observable<boolean>{
        const endpoint = [myPath];
        return this.http
            .get(endpoint)
            .map((resp:any) => resp.SqlResponse === "1");
    }


createNewUser(){

    checkIfUserExists().subscribe(result => 
       {console.log('User status: ', result);
        let tempCheck = result;  
        this.userCheck = result;
       });

}

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

Properly passing props to child components in React with TypeScript. Resolve Error ts(2322)

I am facing an issue where my code works perfectly in Javascript, but encounters problems when converted to Typescript. Despite the complexity of the question, it actually boils down to a simple query. I just wanted to share the functional JS code as a sol ...

The values of object keys are printed in a random order

Hey everyone, I have an object that looks like this var dates = { '2021-09-15': 11, '2021-09-16': 22, '2021-09-17': 38, '2021-09-18': 50, '2021-09-19': 65 }; I am trying to display the valu ...

Angular: ChangeDetection not being triggered for asynchronous processes specifically in versions greater than or equal to Chrome 64

Currently, I'm utilizing the ResizeObserver in Angular to monitor the size of an element. observer = new window.ResizeObserver(entries => { ... someComponent.width = width; }); observer.observe(target); Check out this working example ...

The file functions/lib/functions/src/index.ts is missing, preventing the deployment of Cloud Functions

Whenever I attempt to deploy my Firebase cloud functions, I encounter the following error. Expected outcome: Successful deployment of functions. Error: Error: An issue occurred while reading functions/package.json: functions/lib/index.js is missing and ...

`Angular2 - exploring the complexities of function scope`

I'm facing a challenge while working on my Angular2 Sample with the http module. Here is a snippet from my component: app.loginComponent = ng.core.Component({ selector: 'login', templateUrl: 'app/login/login.html&ap ...

What is the best way to combine TypeScript output while maintaining node import integrity?

Currently, I am combining the results of the typescript compiler using this particular technique. However, this process is causing issues with the imports of relative path modules in Node. The code below compiles and merges successfully; // Group.ts clas ...

Is the component experiencing issues with its style functionality?

I am attempting to add CSS styles to app.component.ts using the :host property, but I am not seeing the desired results. The CSS is being applied, but not correctly. .ts export class AppComponent { title = "Default Title" data = 'This is defaul ...

Creating a JSON object from two arrays is a simple process

Consider the following two arrays: let values = ["52", "71", "3", "45", "20", "12", "634", "21"]; let names = ["apple", "orange", "strawberry", &q ...

The initial rendering of components is not displayed by Vue Storybook

The functionality of the storybook is effective, but initially, it fails to "render" the component. By examining the screenshot, we can deduce that the component-template is being utilized in some way, as otherwise, the basic layout of the component would ...

Using the 'disabled' parameter in the form state object does not have any effect on the FormControl constructor

We've encountered a similar issue in the past: It seems like the disabled attribute is being used with a reactive form directive. If you initialize this control with the disabled property set to true in your component class, Angular will automatical ...

How to dynamically retrieve values from a const object literal using TypeScript

Currently, I am utilizing a TypeScript library known as ts-proto, which is responsible for generating TypeScript code. The resulting generated code resembles the following: //BasicMessage.ts export interface BasicMessage { id: Long; name: string; } ...

When I receive a 404 response from the API, I aim to start my observable

How can I trigger my observable initialization when receiving a 404 response from the API? The code snippet below is not working as expected. const urlParams = { email: this.email }; this.voicesProfileObservable$ = this.service.request<any>( AVAI ...

Angular 12 - Directing users to different views depending on their roles

In my situation, the Admin role login will be able to access the Home and UserView Component. After logging in, an Admin will automatically be taken to the Home component. On the other hand, the User role login will only have access to the UserView compone ...

Error: Unable to access the 'myDate' property as it is not defined

I've been working on a simple code, but I keep encountering a browser error. The expressjs logs also show an error message. TypeError: Cannot read property 'myDate' of undefined at getReportTable (XXX\dist\controllers&bsol ...

Angular firing off select option with object properties

Within my Angular application, I am faced with a situation involving a <select> element that contains a list of <option> elements whose values are associated with objects. My goal is to capture the last selected value using the following code: ...

Fixing a wrong path in the problem matcher of vscode while compiling using $tsc-watch: A step-by-step

My project workspace directory can be found at C:\salix\fantasy. The TypeScript configuration file is located at C:\salix\fantasy\tsconfig.json Despite my efforts, I'm struggling to have the problem matcher for my project dir ...

How to add an item to an array in JavaScript without specifying a key

Is there a way to push an object into a JavaScript array without adding extra keys like 0, 1, 2, etc.? Currently, when I push my object into the array, it automatically adds these numeric keys. Below is the code snippet that I have tried: let newArr = []; ...

Challenges with Property Decorators in Angular 6

Hello there, I've been testing out this sample decorator code and encountered an issue that I can't seem to figure out. The error message I received was "cannot read property 'firstname' of undefined". It appears that the 'this&apo ...

Retrieve a singular item using an HTTP GET request in Angular utilizing RxJS

I am currently working on implementing a feature on my website where users can enter an object's id and see the details of that specific object displayed. I have managed to fetch and display Observables for utilizing in *ngFor loop, but even a single ...

Troubleshooting: Prettier Extension Compatibility Issue in VS Code with Create-React-App and Typescript Template

I'm currently in the process of setting up my application using the Create-React-App startup package with the TypeScript template. Everything goes smoothly during the initial installation. However, when I attempt to use the Prettier Code Formatter ext ...