What is the solution for this problem in TypeScript involving an API service call?

Trying to utilize the API Service to fetch data and display the response as an object created by a class constructor

Currently executing a Typescript code that interacts with the API Service

import * as request from "request";
import { Users } from "./Users";

export class GitubHubApiService{
    getUserInfo(username : String){
   let options : any = {
       headers:{
       "User-Agent" :"request"
    },
    json : true
   }
        request.get("https://api.github.com/users/"+ username ,options,(error:any , Response : any,body: any) => {
            console.log((body));

        let user = new Users((body));
        console.log(user);
        })
    }
}

 This class forms the object using the response data from the API Service call.

export class Users{

    login : String;
    fullName : String;
    repoCount : number;
    followerCount : number;


    constructor(userRes :any){
        this.login = userRes.login;
        this.fullName = userRes.name;
        this.repoCount = userRes.public_repos;
        this.followerCount = userRes.followers;


    }

}

Users { login: undefined, fullName: undefined, repoCount: undefined, followerCount: undefined }

Answer №1

It is not recommended to directly assign values like this, consider using getters and setters instead

 import * as request from "request";
    import { Users } from "./Users";

        export class GitubHubApiService{
            getUserInfo(username : String){
           let options : any = {
               headers:{
               "User-Agent" :"request"
            },
            json : true
           }
                request.get("https://api.github.com/users/"+ username ,options,(error:any , Response : any,body: any) => {
                    console.log((body));

                let user = new Users();
                user.data = body;
                console.log(user.data);
                })
            }
        }

This class creates an object using the response from the API Service call by utilizing get and set methods

    export class Users{

        login : String;
        fullName : String;
        repoCount : number;
        followerCount : number;


        constructor(){

        }
    set data(userRes :any) {
               this.login = userRes.login;
                this.fullName = userRes.name;
                this.repoCount = userRes.public_repos;
                this.followerCount = userRes.followers;

    }
get data() {
return { login: this.login, fullName: this.fullName, repoCount:this.repoCount, followerCount: this.followerCount}
}

}

I have a concern about not following best practices when directly assigning values, consider using getters and setters

 export class GitubHubApiService{
        getUserInfo(username : String){
       let options : any = {
           headers:{
           "User-Agent" :"request"
        },
        json : true
       }
            request.get("https://api.github.com/users/"+ username ,options,(error:any , Response : any,body: any) => {
                console.log((body));
            let user = { login: body.login, fullName: body.name, repoCount: body.public_repos, followerCount:followers }
            console.log(user);
            })
        }
    }

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

Using Typescript, pass a Sequelize model as a property in NodeJS

Currently in the midst of a project using Node, Typescript, and Sequelize. I'm working on defining a generic controller that needs to have specific functionality: class Controller { Schema: <Sequelize-Model>; constructor(schema: <Sequel ...

What is the best way to merge an array of objects into a single object?

Is there a way to dynamically convert object1 into object2, considering that the keys like 'apple' and 'water' inside the objects are not static? const object1 = { apple:[ {a:''}, {b:'&apos ...

How can we effectively divide NGXS state into manageable sections while still allowing them to interact seamlessly with one another?

Background of the inquiry: I am in the process of developing a web assistant for the popular party game Mafia, and my objective is to store each individual game using NGXS. The GitLab repository for this project can be found here. The game includes the f ...

Strategies for evaluating a Promise-returning imported function in Jest

I am currently facing an issue with a simple function that I need to write a test for in order to meet the coverage threshold. import { lambdaPromise } from '@helpers'; export const main = async event => lambdaPromise(event, findUsers); The ...

Issue with the physical back button on Android devices

Whenever I press the physical Android Button I encounter the following error: While executing, an unhandled exception java.lang.IndexOutOfBoundsException: setSpan (2..2) goes beyond length 0 Here is my app.routing.ts import { LoginComponent } from " ...

What is the best way to dynamically import two css frameworks in React?

Currently, I am involved in a project that requires me to incorporate a button for toggling between Bootstrap and Foundation at the request of my client. After exploring several alternatives, I have determined that utilizing hooks to manage the state of e ...

A guide on displaying data from objects containing arrays in React using TypeScript

Hey there! I'm currently facing a challenge in rendering values within an object containing arrays. Let me show you an example of the object structure: data { info1: [{note: "this is note 1", status: true}], info2: [{note: "this i ...

Utilizing the namespace importation method correctly

How can I efficiently utilize classes from a namespace that may be the same or different from the current file's namespace? I currently have the following two files. TypeA.ts: export namespace Game { @ccclass export class TypeA extends cc.Component ...

Angular - Error: Object returned from response does not match the expected type of 'request?: HttpRequest<any>'

While working on implementing an AuthGuard in Angular, I encountered the following Error: Type 'typeof AuthServiceService' is not assignable to type '(request?: HttpRequest) => string | Promise'. Type 'typeof AuthServiceServic ...

Authentication of users using NextJS Dashboard App API

I am currently following this tutorial, but instead of fetching data via a PostgreSQL request, I want to utilize an API. When I call an async function with await, it initially returns undefined and then the user object after receiving a response from the ...

An issue occurred during the project compilation using npm

My project installation process is giving me some trouble. Initially, when I run npm install, it successfully installs all the dependencies. However, when I proceed to execute npm run compile, I encounter an error. Below is the log file for a better under ...

Creating trendy designs with styled components: A guide to styling functional components as children within styled parent components

I am looking to enhance the style of a FC styled element as a child inside another styled element. Check out the sandbox example here const ColorTextContainer = styled.div` font-weight: bold; ${RedBackgroundDiv} { color: white; } `; This resul ...

What is the best way to customize the tooltip in VS Code for TypeScript type aliases?

Here is an issue with the code snippet below: type char = 'a' | 'b' | 'c' | 'd' | 'e' | 'f'; const s: string = 'foo'; const [c]: char = s; // [ERROR]: Type 'string' is not assi ...

Is it possible to retrieve the child state value in the parent component using useRef in ReactJS with TypeScript (hooks)?

I am currently learning Typescript and I am trying to figure out how to pass child state values to the parent component using a ref when a button is clicked in order to update the reducer values. However, I keep running into errors when I try to pass a ref ...

Configuring the array interval in an Angular application

I'm facing an issue while attempting to use the setInterval() function to update text for the user every 3 seconds. My attempt at looping with a for loop has not been successful - I only see 'test 03' and nothing else. I'm struggling ...

Accessing the constants and state of child components within a parent component in React

I've created a MUI TAB component that looks like this <Box sx={{ width: "100%" }}> <Box sx={{ borderBottom: 1, borderColor: "divider" }}> <Tabs value={value} onChange={handleChange} aria-label ...

How can I retrieve the SID received in a different tab using MSAL.js?

I have successfully integrated MSAL into a client-side library, and things are going smoothly so far. My next goal is to enable Single Sign-On (SSO) by following the instructions provided in the documentation at https://learn.microsoft.com/en-us/azure/act ...

Utilizing Typescript's baseUrl compiler configuration for node development

Is there a way for node's module loader to support TS's baseUrl compiler option? With the introduction of the baseUrl compiler option in TS 2, project relative require() and import requests are now possible. However, this feature requires that ...

The error message states that the property 'registerUser' is not found on the class 'UserController'

In the controller file, I exported two functions (registerUser and loginUser) as default. No errors were thrown at that stage, but when attempting to access the routes, an error occurred stating - Property 'registerUser' does not exist on type &a ...

How to use Typescript to find the length of an array consisting of either strings or

I am trying to determine the length of a string or array, stored in a variable with the data type var stepData : string | string[]. Sometimes I receive a single string value, and other times I may receive an array of strings. I need the length of the array ...