Ways to verify the response status in component.ts before triggering another service in Angular 5

Currently, I am retrieving the status code in my service using the following code snippet:

add(new: Add): Observable<Response> {
  return this.http
   .post(this.addURL, new , httpOptions)
     .map((response: Response) => {
      if (response) {
       if (response.status === 200) {
        return [{ status: response.status, response: <Response>response.json() }]
                }
            }
        })
        .catch(this.handleError);
}

In my component.ts file, I am attempting to trigger a list update after successfully adding a new item. Below is the relevant section of my code:

  addDetails(): void {
var new = this.form.value.array;
new = JSON.stringify(this.form.value.array);
this.addService.add(new)
  .subscribe(
  resultArray => this.Response = resultArray,
  error => console.log("Error :: " + error),    
  )
  if(Response.status ===200){
    this.getList();   
  }}

However, I encounter the following error message: Property 'status' does not exist on type 'typeof Response'

Answer №1

Consider returning an Object instead of an Array:

return { status: response.status, response: <Response>response.json() }

If you need to access items in an Array, remember to use the index of the item. For example, when retrieving the status code, make sure to do this inside the subscribe method:

this.addService.add(_new)
  .subscribe(
  resultArray => {
    this.Response = resultArray
    if(resultArray[0].status === 200){
      this.getList();   
    }
  },
  error => console.log("Error :: " + error))

Remember: The subscribe method is asynchronous. You cannot access the returned response outside of it.

Answer №2

Make sure to access the status from the actual Response CLASS, not just any instance of it. Pay attention to the uppercase letters in your code and focus on the typeof Response section for potential errors.

It seems like

if (resultArray[0].status === 200)
should do the trick, although I'm a bit puzzled as to why you're dealing with an array in this context. It might be cleaner to simplify it with something like if (result.status === 200)

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

Azure - deploy a virtual machine and assign an IP address programmatically

I am looking to generate new instances of my image using a nodejs API. I have already set up a network interface (NIC) and an IP for this purpose, but upon creating the VM instance, I am unable to see my public IP address. Below is my typescript code snip ...

Encountering a Problem on Heroku: TypeScript Compilation Error with GraphQL Files - TS2307 Error: Module 'graphql' Not Found or Its Type Declarations Missing

While trying to compile my typescript project with graphql files for deployment on Heroku, I encountered the following error message: node_modules/@types/graphql-upload/index.d.ts(10,35): error TS2307: Cannot find module 'graphql' or its correspo ...

Tips for integrating an arrow function as a property in a functional programming approach using JavaScript or TypeScript

Suppose I were to create a constructor for a functional class with TypeA as an argument, and TypeB representing the type of the class itself. In such cases, I can implement it using: functionName(argument: TypeA): TypeB { this.property = argument; ...

Rollup does not allow the use of self-written component imports in a component library

I am in the process of creating a personalized component library using my own components. However, I am encountering difficulties in the final stage of constructing the library using rollup. The current structure of my folders is as follows: ├── src ...

The statistics for Firebase usage appear to be exaggerated, leaving me curious about the reasons behind the significant increase in reads, sometimes reaching over 70

Considering the recent decision by Google to implement charges for nearly every aspect of Firebase Firestore and Firebase Cloud function usage, it is essential to optimize our code to ensure efficient execution of queries to Firestore. I am currently cond ...

Sending Angular forms to various endpoints

On a page, I have a form consisting of three different groups this.form = this.formBuilder.group({ profile: this.formBuilder.group({ name: [''], description: [''], }), members: this.formBuilder.array([ this.formBu ...

Include a property with a visualizer by employing a command

I am looking to customize an HTML tag by incorporating a new attribute within an Angular 2 component. Consider the original markup utilizing my custom Angular 2 component 'foo' <div foo="x"></div> The goal is for the 'foo&apos ...

Is it possible for me to simply return a finally statement from a function that promises a return value?

Here's a function I'm working with: archive = (): ng.IPromise<any> => { var self = this; return self.setStatus() .then( () => { } ) .finally(() => { self.controls = self. ...

Implementing ExpressJS functionality within a TypeScript class

Searching through numerous examples of ExpressJS and TypeScript, I noticed they all follow a similar pattern: import * as express from "express"; let app = express(); app.use("/", express.static("/")); However, my preference is to employ the class appro ...

Transferring the input element's binding value to the model using ngModel

Just starting out with Angular and I'm having trouble passing an input value to my database model. The firstname from the database is binding properly to the Input element based on the account id, but for some reason, the same input value (AccountName ...

"I am looking for a way to retrieve dynamic data from a (click) event in Angular. Can

Within my component, I have a video loaded in an i tag on a click event. The challenge is accessing the video ID from the video.component.ts file in order to dynamically load a new video. The solution has been elusive so far. <li *ngFor="let video of c ...

What causes TypeScript to malfunction when using spread in components?

What is the reason for typescript breaking when props are sent to a component using a spread statement? Here's an example code snippet: type SomeComponentProps = Readonly<{ someTitle: string }> const SomeComponent = ({ someTitle }: SomeCompo ...

The function is not properly defined for the provided service

I am facing an issue with a service that is provided in app.module.ts and injected into an exported function within the same module. Despite this setup, when running the code inside MSALInstanceFactory, it is indicating that the service is undefined. impor ...

Comparing Javascript's GroupBy function to the LINQ GroupBy in C#

After reviewing the question linked below, we have a follow-up inquiry: Javascript Equivalent to C# LINQ Select We are currently working with Angular 2 and TypeScript. In our scenario, we have an array of objects where each object contains a property na ...

Enhancing Apollo Cache Updates using TypeScript null checks

Currently, I am utilizing apollo codgen to automatically generate types for my graphql queries in TypeScript. However, I have noticed that the generated types contain numerous instances of null values, leading to an abundance of if checks throughout my cod ...

What steps can I take to correct my code so that it only shows a single table?

I'm facing an issue while trying to display my dynamic JSON data. It's rendering a table for each result instead of all results in the same table. My array data is coming from the backend API. const arr = [ { "Demo": [ ...

Is there anyone who can assist in resolving this issue? I've already added the vendor.js file to Index.html

While starting up the application, I encountered this error. I attempted to resolve it by adding the vendor JavaScript in index.html view image description here ...

What steps should I take to fix the routing problems in this Ionic app through an update?

I'm currently experiencing difficulties with an Ionic application development course that is based on Ionic 4 or 5, whereas I am using version 7. Specifically, the issue arises with routing functionality. Upon accessing http://localhost:8101/recipes, ...

Retrieve information from the local storage every second

I have developed a new application using Angular 8. Within this component, I have created a model where users can select an option. I wrote a function in the TypeScript file to store this information in local storage. Now, I need assistance with retrieving ...

Reactify TypeScript: Accurate typings for onChange event

How can I resolve the issues with types for target: { value: any, name: any }? The errors I encounter include Duplicate identifier 'any'. and Binding element 'any' implicitly has an 'any' type.. Additionally, why does the erro ...