Setting up Thrift in an Angular and Electron project

Attempting to incorporate Thrift API calls into my Angular application, I used the following command to generate client files:

thrift-0.18.1.exe -r --gen js:ts <myService.thrift>

The command successfully created both JavaScript (js) and TypeScript (ts) files which were then added into the app. Additionally, the thrift library was installed with pnpm add thrift

import * as thrift from 'thrift';
import { MyServiceClient } from './myService';
import { Injectable } from '@angular/core';

@Injectable()
export class TestMyClient {
    constructor() {
        const host = 'localhost';
        const port = 45000;
        const opts = { transport: thrift.TBufferedTransport, protocol: thrift.TJSONProtocol, headers: { 'Content-Type': 'application/vnd.apache.thrift.json', }, https: true, path: '/url/path', useCORS: true, };

        const connection = thrift.createXHRConnection(host, port, opts);
        const thriftClient = thrift.createXHRClient(MyServiceClient, connection);

        connection.on('error', (err) => { console.error(err); });

        const data = thriftClient.myAPI();
        console.log(`data received: ${data}`);
    }
}

However, upon running the code, an error is encountered:

Uncaught ReferenceError: myService_myAPI_args is not defined

This error seems to be originating from webpack during the bundling process of generated client files. Is there a step missing in the configuration? Any additional setup required?

Answer №1

To improve your code, consider making the following changes

import * as thrift from 'thrift';
import { MyServiceClient } from './myService';
import { Injectable } from '@angular/core';

@Injectable()    
export class TestMyClient {    
    constructor() {    
        const host = 'localhost';    
        const port = 45000;    
        const opts = {     
            transport: thrift.TBufferedTransport,     
            protocol: thrift.TJSONProtocol,     
            headers: { 'Content-Type': 'application/vnd.apache.thrift.json' }, 
            https: true, 
            path: '/url/path', 
            useCORS: true
        };

        const connection = thrift.createXHRConnection(host, port, opts);
        const thriftClient = thrift.createXHRClient(MyServiceClient, connection);

        connection.on('error', (err) => { console.error(err); });

        const args = {};    
        args.myParam = 'my value'; // specify necessary arguments in the args object

        thriftClient.myAPI(args, (err, response) => {
            if (err) {
                console.error(err);
            } else {
                console.log(`data received: ${response}`);
            }
        });
    }
}

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

Troubleshooting: Issue with Button Layout in Ionic's ItemSliding Component

How can I create a list item that allows swiping to reveal an archive button? The requirement is for the icon to appear to the left of the text. I'm referring to the documentation on Button Layout: https://ionicframework.com/docs/api/components/item ...

ESlint is unable to parse typescript in .vue files

After using vue ui to build my project, here is the content of my package.json: "@vue/cli-plugin-eslint": "^4.1.0", "@vue/cli-plugin-typescript": "^4.1.0", "@vue/eslint-config-standard": "^4.0.0", "@vue/eslint-config-typescript": "^4.0.0", "eslint": "^5.1 ...

Error in util.js: process variable is not defined in Angular 15

As I work on integrating the Voice JavaScript SDK into my Angular 15 application, I encountered an error after installing the necessary npm packages. When running the app, a reference error is displayed in the browser console and the UI fails to load. Unca ...

"Exploring the New Feature of Angular 17: Named Router Outlets Implemented

One issue I am facing with my application is the rendering of different pages based on whether a user is logged in or not. The generic pages like the landing or logout page should be displayed within the primary router-outlet when the user is not logged in ...

Using TypeScript to send state through history.push({...})

I recently utilized the history.push method to redirect to a specific URL while passing along some information through the included state. Here's how I implemented it: const history = useHistory() history.push({ pathname: '/someurl/', ...

Display responsive input field based on selected option in ionic2 dropdown menu

When the user selects 'Other' from the dropdown menu using Ionic2 and Angular2, I want to provide them with an option to enter their profession. Here is a visual representation of the select box: https://i.sstatic.net/CRjAl.png Below is the co ...

Enhance the appearance of a custom checkbox component in Angular

I developed a customized toggle switch for my application and integrated it into various sections. Recently, I decided to rework it as a component. However, I am encountering an issue where the toggle switch button does not update in the view (it remains t ...

Leverage the power of TypeScript by enabling the noImplicitAny flag when working

Currently, I am looking to activate the noImplicitAny flag in my compiler. My main issue lies with utilizing lodash/fp as there are no typings available at this moment. Due to this, the compiler is generating errors due to the absence of a definition file ...

Unexpected behavior observed in ng-select when pasting search values

When attempting to update an array of strings acting as the model for an ng-select, the values do not appear correctly in the search box. https://i.sstatic.net/WqdJ6.png The values that are displaying correctly are the ones selected from the dropdown men ...

Protecting Angular Routes: Verifying HTTP-Only Cookie Authentication on the Server- CanActivate Function

I am utilizing an HTTP only cookie for authentication in my server: export const checkCookie = async (req: Request, res: Response) => { const token = req.cookies["token"]; if (!token) { return res.status(401).json({ message: "Unau ...

Unable to dynamically load a script located in the node_modules directory

This particular approach is my go-to method for loading scripts dynamically. import {Injectable} from "@angular/core"; import {ScriptStore} from "./script.store"; declare var document: any; @Injectable() export class ScriptService { private scripts: an ...

While utilizing the imodel.js front-end for designing a custom geometric model, I ran into an issue while trying to display it

Utilizing imodel.js front-end, I was able to design a customized geometric model featuring elements like a collection box. However, when placing the model within the existing SpatialViewState in bim, it failed to display properly in the current view. Sub ...

Launching in dynamically loaded modules with bootstrapping

The Angular Guide explains that during the bootstrapping process, components listed in the bootstrap array are created and inserted into the browser DOM. However, I have noticed that I am unable to bootstrap components in my lazy loaded feature modules. E ...

Make sure that each function within a generic interface is asynchronous

Imagine having an abstract class that accepts a generic type export abstract class RegisterableClass<InstanceType> and a class that implements it like this: class UserService extends RegisterableClass<IUserService> implements IUserService { ...

Utilize ngFor in Angular Ionic to dynamically highlight rows based on specific criteria

I'm working on an application where I need to highlight rows based on a count value using ngFor in Angular. After trying different approaches, I was only able to highlight the specific row based on my count. Can someone please assist me? Check out m ...

If the container encounters an issue while processing asynchronous ngFor directives

Something unexpected is happening in Angular2 when I use an ngIf container with a list created using ngFor. It seems like the view doesn't display items from the observable array the first time they are added after the ngIf container becomes visible. ...

The module 'AppModule' has declared an unexpected value of 'undefined', leading to a SyntaxError within the ZoneAwareError

I encountered an error while running my Angular 2 application using npm version 4.6.1. Despite successful ng build and gulp processes on the project, I am receiving this error. Any insights or assistance would be greatly appreciated. Thank you. @angular/c ...

What is the method to incorporate the current time into a date object and obtain its ISO string representation?

I'm using a ngbDatePicker feature to select a date, which then returns an object structured like this: {year:2020, month:12, day:03} My goal is to convert this date into an ISOString format with the current time. For example, if the current time is 1 ...

When using Angular 2 formControl, manually changing the value may not be detected by the form

Having a simple form (as shown below), I am encountering an issue: Manually entering input value causes form.controls['myValue'].value to change If #myInput value is changed programmatically, the form completely ignores that change What could ...

The type 'Navigator' does not have the property 'userAgentData' in its definition

Since I'm looking to minimize the information provided by navigator.userAgent, I decided to migrate to User-Agent Client Hints. However, I've encountered an error while attempting to do so: https://i.stack.imgur.com/lgIl7.png Could someone plea ...