Obtain the property value from an Angular 6 HTTP response object

I've been on the lookout, but I just can't seem to find a solution that works for me.

So, here's the situation: I have an http post service where I receive responses in object format. My code currently looks like this:

data.subscribe(data => {
   let results;
   this.results = data;
   this.processResults(this.results);
}


processResults(obj: Object) {
   console.log(obj); 

  // Here's the challenge - I need to extract the value stored in resultCodeConstant from the object. I attempted using functions like filter and find, but kept running into errors stating that it doesn't exist on type Object
  // let item = obj.filter(element.name == 'resultCodeConstant')
}

The response I get from the http subscribe call looks something like this within the 'obj' variable:

{
   authorizationToken: "qTYLf6f...", 
   secretQuestionId: null,
   secretQuestionSentence: null,
   resultCodeConstant: "AUTHORIZED",
   userAccountState: "active",
   …
}

Is there a way for me to specifically target and retrieve the value I need from this result? Do I need to implement some kind of loop?

Answer №1

This is how I tackled it:

fetchDataFromServer(id) {
    this.http.get('https://localhost:44318/download/' + id)
        .subscribe(Response => {
            this.docData = Response;
            this.documentList= this.docData.results[0].fileContent;
        });
}

Answer №2

In order to access the authorizationToken property of your object, make sure to define it with the type 'any' like in the example below:

processResults(object: any) {
  console.log(object.authorizationToken); 
}

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

Organize nested tuples and maintain their sequence

I am attempting to achieve a functionality similar to the following: type Type = object; type TypeTuple = readonly Type[]; function flattenTuples<T extends readonly (Type | TypeTuple)[], R = Flatten<T>>(...tuples: T): R { // code to flatten ...

Exploring NestJs: A comprehensive guide to testing response controllers

I am looking to use Jest to test the responses from my API. This method is from my controller. @Post('send-banana') async sendBanana( @Body() request: BananaRequest, @Res() res: Response, ) { const responseCodeService = await th ...

Retrieve an object containing properties specified in the function's parameter list

I am currently working on developing a function that can dynamically create and return an object with properties based on an array of strings provided as parameters. type Foods = 'apple' | 'banana' | 'pear'; function foodObje ...

Dividing component files using TypeScript

Our team has embarked on a new project using Vue 3 for the front end. We have opted to incorporate TypeScript and are interested in implementing a file-separation approach. While researching, we came across this article in the documentation which provides ...

How can I invoke a TypeScript function within HTML code?

Currently, I am working on an Angular project where I have implemented two straightforward methods in a TypeScript file: findForm(text: string, forms: Array<string>) { for (let form of this.forms) { if (text.includes(form)) { retur ...

Error encountered: ⨯ Compilation of TypeScript failed

My current project is utilizing Node.js in conjunction with TypeScript An issue has arisen during compilation within my Node.js application: E:\NodeProjects\esshop-mongodb-nodejs\node_modules\ts-node\src\index.ts:859 ret ...

Bringing in numerous modules within Angular

Currently, I am in the process of developing an application using Angular 4 and Angular Material. Each Material directive necessitates importing its module individually. For instance, when working on a navigation bar, the nav.module.ts file begins to take ...

Is TypeScript's Structural Typing the exception to the rule?

Let me illustrate two scenarios where I encountered difficulties. The first example involves two points: one in 2d and one in 3d: type Point2D = { x: number, y: number }; type Point3D = { x: number, y: number, z: number }; let point2D: Point2D = { x: 10, ...

Executing a function within the same file is referred to as intra-file testing

I have two functions where one calls the other and the other returns a value, but I am struggling to get the test to work effectively. When using expect(x).toHaveBeenCalledWith(someParams);, it requires a spy to be used. However, I am unsure of how to spy ...

React application facing a problem with bracket notation in Typescript

After creating a form state to store and update input changes, I encountered an issue: const [form, setForm] = useState({ user: '', email: '', password: '', }); I then wrote a function to handle form changes: const handle ...

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 ...

There seems to be an issue with the API response being undefined when displayed on

After retrieving a list of items from my MySQL database, I noticed that when I click the 'edit' button by ID, the fields are not being filled with the data as expected. Instead, I am seeing 'undefined' in my console. Interestingly, when ...

Error in Visual Studio: ASP.NET Core application integrated with Angular is unable to run the API

I recently went through a tutorial on creating an ASP.NET Core app with Angular in Visual Studio, Although I successfully got the Angular project running, I encountered an issue where the API component did not run. Despite trying to access the API endpoin ...

Angular 5 throws EmptyError when trying to create child routes with no elements in the sequence

I am facing a problem with navigating from the login page to the dashboard page when using children in routing. Here is my current routing configuration: const appRoutes: Routes = [ { path: '', redirectTo: 'login', pathMatch: 'ful ...

Steps to apply a decorator to a function that is not a nestjs route

NestJS Hello there! I am currently facing an issue where I need to apply a decorator to a function that is not serving as an endpoint or route. To illustrate, here is what I have in mind: class Controller { @Get('/') firstMethod() { ...

Incorporate a New Feature into my NPM Package

I've been searching high and low for an answer to this, but I'm still stuck. I'm working on a module in Angular 2 with ng-module, and everything is functioning properly. However, I'm struggling to assign a property to another property w ...

Receiving contextual information from Microsoft Teams within an Angular application integrated as a tab

I am currently integrating an Angular website into a Microsoft Teams tab. In order to perform certain computations, I need to retrieve the Team ID. To achieve this, I have recently added npm install --save @microsoft/teams-js. Below is the code snippet th ...

What is the best way to extract value from subscribing?

I attempted to accomplish this task, however, I am encountering issues. Any assistance you can provide would be greatly appreciated! Thank you! export class OuterClass { let isUrlValid = (url:string) => { let validity:boolean ...

Handling Errors in Angular 4

If a client sends a POST request with a LicenseNumber that already exists in the database (and must be unique), the server will respond as follows: {"errorCode":"Validation Error", "errorMessage":"Invalid inputs.", ...

Unable to locate the 'functions scss error within the Angular application

Having recently created a fresh angular 7 application and incorporating scss, I encountered an error after building the application. The style.scss class contains the following import: @import '../node_modules/bootstrap/scss/bootstrap.scss'; I ...