Angular is not providing the anticipated outcome

I'm new to Angular (7) and I'm encountering an issue while trying to retrieve the status code from an HTTP request. Here's the code snippet used in a service :

checkIfSymbolExists() {
     return this.http.get(this.url, { observe: 'response' })
      .subscribe(response => {
        return response.status;
      });
  }

The returned value is then utilized in a method within one of my components in the following manner :

onSubmit() {
    console.log(this.stocks.checkIfSymbolExists());
}

Unexpectedly, instead of receiving a numerical value as desired, I am getting an object with the following structure:

Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …}
closed: true
destination: SafeSubscriber {closed: true, _parent: null, _parents: null, _subscriptions: null, syncErrorValue: null, …}
isStopped: true
syncErrorThrowable: true
syncErrorThrown: false
syncErrorValue: null
_parent: null
_parentSubscription: null
_parents: null
_subscriptions: null
__proto__: Subscription

Interestingly, when I utilize console.log instead of simply returning response.status, I do see the expected 200 status code displayed (a number, not an object).

Any insights on why the behavior changes when returning the value of response.status? Thank you.

Answer №1

You're not approaching it the right way. Here's a more effective method to achieve this:

Instead of subscribing directly to http.get, you should return a mapped response by using .pipe(map(...)):

import { map } from 'rxjs/operators';
...
checkIfSymbolExists() {
  return this.http.get(this.url, { observe: 'response' })
    .pipe(
      map(res => (res.status === 200))
    );
}

Next, you should return the observable from checkIfSymbolExists and then subscribe to it in the onSubmit method:

onSubmit() {
  this.stocks.checkIfSymbolExists()
    .subscribe(res => console.log(res));
  // If status is 200, true will be printed. Otherwise, false.
}

Explanation:

The purpose of your service method checkIfSymbolExists() is to provide the Component with the desired data. The Component doesn't need to know the source of this data; it just needs to receive a boolean upon subscribing to the Observable returned by checkIfSymbolExists()

In checkIfSymbolExists(), we have added the option to observe the complete response by utilizing { observe: 'response' }. Through the map operator, we are checking for the value of res.status to determine if it equals 200.

Based on the comparison result of ===, map will return either true or false depending on whether the status is 200 or not.

I hope this clarifies the process for you.

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

Please ensure that all fields in the form are filled out before clicking the enable button

Is it possible to enable the button only when all fields are filled out in a form? It's easy if there's just one field, but I have multiple fields with a select field as well. I'm not sure how to do this. Here's the form I've creat ...

What is the most efficient way to dynamically load a script file before proceeding with the rest of the code execution?

In my Angular home.component.ts file, I have added the script loading code as shown below: export class HomeComponent { constructor() { this.loadDynamicScript(); } public loadDynamicScript() { var script = document.createElement(&a ...

Click on the input to add or remove a value

I have written a code where, on click, I insert an email address into a field. However, what I am trying to achieve is that upon the next click on the same field, it will remove the email if one already exists in the input. Below is my current code snippe ...

"Enhance your website with a sleek Bootstrap navigation system featuring dividers and

Need help with creating a Bootstrap nav menu similar to this design made in Photoshop? Wondering about the best way to position the logo and create dividers between menu items like shown in this image. Here's the HTML code currently being used: & ...

Alternatives to using $.getJSON()

When utilizing jQuery within the React/Redux environment, what alternative library is typically used for handling straightforward REST calls instead of $.getJSON or $.postJSON? Is there a widely-used option that functions similarly to node's http mod ...

Dynamically injecting a JavaScript script within a Vue.js application

Is there a way to dynamically load a JavaScript script within a Vue.js application? One approach is as follows: <script async v-bind:src="srcUrl"></script> <!--<script async src="https://cse.google.com/cse.js?cx=007968012720720263530:10 ...

Adjust the href link value when a new option is selected

I currently have a select element displayed below. Next to it, there is a link that sets the eID value to a session value. However, I want this value to be updated dynamically whenever a different eID value is selected from the dropdown. Although I can r ...

Increasing the sms counter in javascript once it reaches 160 characters

I am facing an issue with my two counters that are used to track the number of characters in a message. Everything works fine until 160 characters, but after that point, the first counter stops at 0 instead of resetting back to 160 and decreasing from ther ...

The function dispatch is not recognized and will be removed from the database. An error will be generated indicating that dispatch is not a valid function

There seems to be an issue with the delete function in Ticket Actions as it is giving an error that dispatch is not a function. The goal here is to enable users to delete specific tickets by clicking on them and also provide an option to edit the ticket. ...

The themes showcased in the Bespoke.js documentation and demo exhibit unique designs

Recently, I stumbled upon an incredible HTML5 framework for presentations. For more information, you can check out the documentation here. You can also view a demo of the framework by visiting this link. However, I was disappointed to find that the caro ...

Creating a JSON File with an Illustrator Script

Currently, I've been working diligently on developing a system that allows me to export my swatches from Illustrator as a JSON object. This will greatly simplify the process of updating my App. By utilizing the illustrator scripting API, I've suc ...

Securing string parameters in Django templates for JavaScript function usage

Can anyone help me with a JavaScript function that is returning a set of objects? return Func("{{id}}", "{{name}}") I'm encountering an issue when passing strings that contain quotes, such as "Dr.Seuss' "ABC""BOOk"", which leads to invalid synt ...

Is it possible to run Next.js 13 with React.js version 17?

Can Next.js 13 be used with React version 17? I upgraded my Next.js to version 13 and encountered a minimum requirement of React version 18, which is not compatible with my codebase. Is it possible to use Next.js 13 with React version 17 instead? ...

Oops! Looks like you forgot to include the "reducer" argument. It is necessary and should be either a function or an object of functions that can be passed to combineReducers

1 I'm currently working through the Redux tutorials on their website and I'm encountering an issue when trying to use combine reducers. When I run my code without using combine reducers, everything works fine. However, as soon as I include the s ...

Tips for updating a column with just one button in AngularJS

On my list page, there is an Unapproved button. I am new to angular and struggling to figure out how to retrieve the post's id and update the corresponding column in the database to mark it as approved. Can someone provide guidance on how to accomplis ...

Tips for setting up a range slider for decimal numbers

I have implemented the following code for a range slider. It works perfectly fine for integer values like 1 and 100, but I am facing issues when trying to use decimal values. I attempted to substitute 1 with 0.1 but it did not yield the desired result. ...

Typescript encounters ERROR TS1128: Expecting a declaration or statement

Having trouble with a TypeScript error in my game-details.component.ts file that I've been trying to fix for a couple of hours. It's showing up at line 26, column 54 and everything seems correct to me. Interestingly, when I press CTRL + S in my ...

Transclusion with multiple slots in AngularJS

Attempting to incorporate a component in AngularJS 1.5.8 with multi-slot transclusion. The test performs well when utilizing a directive, however, with a component, it appears that the slot cannot be located!. This is how the component is declared app. ...

The slash character is escaped by the RegExp constructor, but the dot character is

Consider the following code: console.log(new RegExp('.git')); console.log(new RegExp('scripts/npm')); which produces the following output: /.git/ /scripts\/npm/ The puzzling question here is - why does it escape the slash in &a ...

The data type 'StaticImageData' cannot be converted to type 'string'

I've hit a roadblock with interfaces while working on my NextJS and TypeScript project. I thought I had everything figured out, but I'm encountering an issue with the src prop in my Header component. The error messages I keep receiving are: Typ ...