Retrieving a portion of the response with Angular's HttpRequest

I am facing an issue with a request where I need to upload a file and receive a JSON response. The problem arises when trying to access a specific part of the response, namely body.path. Despite my efforts, I keep encountering an error stating that the path does not exist.

The response I receive is as follows:

{"success": 1, path: "somestring"}

I attempted using e.body?.path, but to no avail.

let req = new HttpRequest('POST', globalVar.host + "/upload.php", formData, { responseType: "json", reportProgress: true});

this.http.request(req)
  .subscribe(e=>{
    if(e.type === HttpEventType.UploadProgress){
      const percentDone = Math.round(100 * e.loaded / e.total);
      this.uploadProgress = percentDone;
    }
    if(e.type == HttpEventType.Response){
      this.fileLocation.emit({"path": e.body.path, "next": true})
    }
  })

When using e.body?.path, I encounter the following errors at build time:error TS1005: ':' expected. and

error TS1003: Identifier expected.

e.body.path results in the error message

error TS2339: Property 'path' does not exist on type '{}

Answer №1

Remember to enter either the body or response type

Method #1 (simplest way)

this.fileLocation.emit({"path": (e.body as any).path, "next": true})

Technique #2

interface MyResponse
{
 success: number;
 path: string;
}

this.fileLocation.emit({"path": (e.body as MyResponse).path, "next": true})

Approach #3 (my preferred method)

Specify the response type directly

this.http.request(req)
  .subscribe((e: HttpEvent<MyResponse> ) //<== type here
=>{
    if(e.type === HttpEventType.UploadProgress){
      const percentDone = Math.round(100 * e.loaded / e.total);
      this.uploadProgress = percentDone;
    }
    if(e.type == HttpEventType.Response){
      this.fileLocation.emit({"path": e.body.path, "next": true})
    }
  })

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

arrange the elements in an array list alphabetically by name using the lodash library

Is there a way to alphabetically sort the names in an array list using JavaScript? I attempted to achieve this with the following code: const sample = [ { name: "AddMain", mesg: "test000" }, { name: "Ballside", ...

Send information to the main application component

Can data be passed two or more levels up from a Child Component to the App Component? https://i.stack.imgur.com/JMCBR.png ...

How can we efficiently determine if a background image is broken in Angular 5 and substitute it with a default image?

When working with Angular 2+, we often use the <img> tag to display images using a syntax like <img [src]="myDp" (error)="myDp='assets/media/user/default_dp.jpg'">, where myDp contains the relative path to the image on the server. Is ...

What is the best way to make mouse and touch events trigger responses in Angular versions 9 and above?

I've been searching high and low for a library or tried-and-true method to handle common user events reactively, but unfortunately my quest has come up empty. After some digging, I stumbled upon what seemed like a solid solution: https://github.com/t ...

I'm encountering an issue with my React 18 application using TypeScript: the module './App' cannot be found

Encountering an issue while attempting to update to react 18. I'm curious if this problem is related to my file types. I am using Typescript, so do both the app and index files need to have a .tsx extension? Both the app and index files are located ...

Ensuring page is fully loaded in a Bootstrap application using Protractor

What is the best approach for waiting for page load in a Bootstrap App while using Protractor? I've been searching for helpful information but haven't found much. ...

Badging with Angular, HTML, and Bootstrap

I've been attempting to integrate Bootstrap 5's badges into my Angular application, but they don't seem to be displaying correctly together. While using Angular 13, the html within the app-root component appears clustered without proper for ...

The issue encountered during a POST request in Postman is a SyntaxError where a number is missing after the minus sign in a JSON object at position 1 (line 1

Running my API in a website application works flawlessly, but encountering SyntaxError when testing it in Postman - specifically "No number after minus sign in JSON at position 1" (line 1 column 2). The data is correctly inputted into the body of Postman a ...

The introduction of an underscore alters the accessibility of a variable

When working in Angular, I encountered a scenario where I have two files. In the first file, I declared: private _test: BehaviorSubject<any> = new BehaviorSubject({}); And in the second file, I have the following code: test$: Observable<Object& ...

Are you on the lookout for an Angular2 visual form editor or a robust form engine that allows you to effortlessly create forms using a GUI, generator, or centralized configuration

In our development team, we are currently diving into several Angular2< projects. While my colleagues are comfortable coding large forms directly with Typescript and HTML in our Angular 2< projects, I am not completely satisfied with this method. We ...

Challenges with invoking functions within ngFor loop during unit testing in Angular 12

I am currently learning about unit testing and I am facing an issue with calling a function inside an *ngFor loop in an Angular 12 application. I have an observable that contains an array of objects and it is working correctly, iterating through the data p ...

Typescript: Deciphering how to interpret a string with a mix of characters and numbers

Is there a way in TypeScript to add 40 to a variable of type string | number, and return a result as a string | number? My initial approach was to parse the variable to a number, then perform the addition, but how can I ensure that the variable is proper ...

Exported data in Vue3 components cannot be accessed inside the component itself

Essentially, I'm working on creating a dynamic array in Vue3. Each time a button is clicked, the length of the array should increase. Below is the code snippet. <div class="package-item" v-for="n in arraySize"></div> e ...

Retrieving information from Next.js and Typescript with the help of getStaticProps

I've been working on a personal project with Next.js and TypeScript. I'm attempting to fetch data from an API and then map the items, but I'm running into issues. When I use console.log, it returns undefined. The file is located in the pages ...

Guide to successfully passing a function as a prop to a child component and invoking it within Vue

Is it really not recommended to pass a function as a prop to a child component in Vue? If I were to attempt this, how could I achieve it? Here is my current approach: Within my child component - <template> <b-card :style="{'overflow-y&apo ...

Creating string enums in NextJS with TypeScript

I am working on my nextjs application and I have a component with a prop that is a string. I decided to create an enum, so I attempted the following: enum Label { dermatology = 'Dermatologi', psychology = 'Psykologi', rheumatology = ...

Minimize the amount of information retrieved and shown based on the timestamp

I am currently working on storing and retrieving the date of a user request. For creating the timestamp, I use this code: const date = firebase.firestore.FieldValue.serverTimestamp(); This is how I fetch and display the data: <tr class="tr-content" ...

Managing variables or properties that are not defined in ES6

Currently, I am utilizing Angular and Firebase Firestore in my project. However, the question posed could be relevant to Typescript and pure Javascript as well. The functionality of my application relies heavily on the data retrieved from Firestore. A sim ...

Using both <router-outlet> and <div ng-view> in AngularJS and Angular for routing simultaneously

Within my app component (originally an Angular 2 component but downgraded for index.html), I have the following code: <router-outlet></router-outlet> <div ng-view></div> I followed the instructions in the "Dividing routes betw ...

Different approach to including labels on scatter plot without relying on "chartjs-plugin-datalabels"

I need help adding labels to the pink scatter dots without affecting the green bars in the horizontal bar chart generated by ngchart. You can see an image of the chart here. Whenever I try to include the following code: import ChartDataLabels from "c ...