Is there a way to efficiently convert several strings within an object that has been retrieved from an HTTP request into another language, and subsequently save this object with the

Is there a way for me to translate some strings in an object before storing it in another http request using the Google Translate API? I am currently getting the object from one http request and saving it with a put method. How can this be achieved?

service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';

import { BaseApi } from '../../../../laas/base-api.service';
import { ApplicantService } from '../../../../laas/applicant.service';
import { environment as ENV } from '../../../../../environments/environment'

@Injectable()
export class NregaService {

  private applicantId: string;
  private baseUrl: string;

  constructor(
    private http: HttpClient,
    private api: BaseApi,
    private applicant: ApplicantService
  ) {
    this.applicantId = applicant.getApplicantID()
    this.baseUrl = `/applicants/${this.applicantId}/id/nrega`;

  }

  get() {
    return this.api.newGet(this.baseUrl);
  }

  save(type, data) {
    return this.api.put(this.baseUrl, { type: type, data: data });
  }

  translate(q) {
    const translateUrl = ENV.googleAddress.translateUrl;
    const apiKey = ENV.googleAddress.apiKey;
    const target = 'en';
    const model = 'base';
    return this.http.post(`${translateUrl}${apiKey}`, { q, target, model }).map(res => {
      const value = res['data'].translations[0];
      console.log(`Translated ${q}:`, value);
      return value.translatedText;
    });
  }

  verify(id) {
    return this.api.post('nrega', { jobcardid: id }).map(result => {
      if (typeof result === typeof '') {
        throw result;
      }
      
      // Code for processing result omitted for brevity

      return data;
    });
  }

}

If I try to use the translate method within the service itself without the .subscribe method, I encounter an error. Is there a way to translate multiple strings within the service before returning the data to the component?

Answer №1

It seems like the solution you are searching for involves utilizing the Rxjs map operator.

To begin, make sure you import this operator in your service.ts file.

import 'rxjs/add/operator/map';

If I understand correctly, you wish to translate certain strings when your component calls the get method, after receiving data from the server but before sending it back to the component.

component > service.get() > http request > data received from server > translate > data sent to the component

If my assumption is right, all you need to do is use the map operator:

get() {
  return this.api.newGet(this.baseUrl)
    .map(data => this.translate(data));
}

Consider a SourceData type and a ModifiedData types. By using the map operator, you can return an Observable<ModifiedData> instead of the original Observable<SourceData>. Refer to the documentation here for a more detailed explanation.

Additionally, you can perform the translation when your save method is invoked.

save(type, data) {
  data = this.translate(data)
  return this.api.put(this.baseUrl, { type: type, data: data });
}

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

Launching Angular 2 Application on Azure Cloud

I have recently been diving into the world of Angular 2 and Azure. Following the steps outlined in the Angular 2 Tutorial, I was able to successfully run my application locally without any issues. After deploying the app to Azure, I encountered a problem. ...

Is it possible to lengthen a function in TypeScript?

I am part of a team responsible for maintaining a unique JavaScript library that generates spy functions. These spy functions are designed to allow users to monitor how a function is called, primarily used in the context of unit testing. Our library creat ...

Creating dynamic routing functionality in Angular 8 allows for a more personalized and

I am struggling with setting up routing in Angular 8. Here is how I am trying to do it: 'company/:id/activity' 'company/:id/contacts' However, I am not receiving any params in the activatedRoute: this.activateRoute.params ...

Exploring the potential of Socket.io and Angular with the seamless integration of

I have encountered an issue regarding the use of async pipe with Observables. Initially, I assumed that returning an Observable from my service on a socket.on event would suffice. However, it appears that my approach is incorrect. Can you guide me on the c ...

webpack is having trouble compiling TypeScript with React components

I've been working on setting up a TypeScript React project with webpack. I followed the TypeScript Tutorial, but I keep running into an error message that says `module parse failed: ... you may need an appropriate loader` Interestingly, I can success ...

What is the best way to invoke a method within the onSubmit function in Vuejs?

I am facing an issue with a button used to log in the user via onSubmit function when a form is filled out. I also need to call another method that will retrieve additional data about the user, such as privileges. However, I have been unsuccessful in makin ...

Troubleshooting: Why is Angular2 ngClass malfunctioning?

I am having trouble adding a class based on a condition <tr *ngFor="let time of times; let i = index"> <td [ngClass]="{'red-time':checkInvalid(time['Proles Arrive'])}">{{time['Proles Arrive']}}</td& ...

The role of providers in Angular applications

After creating a component and service in my project, I followed the documentation's instruction to include the service in the providers metadata of the component for injection. However, I found that it still works fine even without mentioning it in t ...

The various types of Angular 2 FormBuilders

As I delved into learning Angular 2, I initially came across ngModel, and later discovered FormGroup/FormBuilder which seemed more suitable for handling complex forms. However, one downside that caught my attention was that by using FormBuilder, we sacrifi ...

What is the best way to retrieve an object within a class?

Exploring a Class Structure: export class LayerEditor { public layerManager: LayerManager; public commandManager: CommandManager; public tools: EditorTools; constructor() { this.commandManager = new CommandManager(); this.lay ...

How to Measure the Length of an Undefined Value in Jasmine Angular Unit Tests

Here's a function that I have: updateParts(enviromentContainsAllParts: PartsContainsAllParts): Observable<boolean> { const enviroment = cloneDeep(this.enviroment); enviroment.containsAllPart = enviromentContainsAllParts.containsAllPart ...

The specified '<<custom component name>>' argument does not match the 'Type<<custom component name>>' parameter

I'm currently facing an error that indicates a type parameters mismatch, but I can't pinpoint where in the process it's happening. Argument of type 'ModalUserInfoComponent' is not assignable to parameter of type 'Type<Mo ...

Issue with Docker setup for managing a PNPM monorepo

As a newcomer to Docker, I am attempting to configure my fullstack API REST project. Within my PNPM workspace, I have two applications - a frontend built with Angular and a backend developed using AdonisJS. My goal is to create a Docker configuration for P ...

When using Typescript, I am encountering an issue where declared modules in my declaration file, specifically those with the file

One of the declarations in my ./src/types.d.ts file includes various modules: /// <reference types="@emotion/react/types/css-prop" /> import '@emotion/react'; import { PureComponent, SVGProps } from 'react'; declare mod ...

Combining union types with intersection operators in Typescript

Here's a concept for an event handling system: type EventMap = Record<string, any>; type EventKey<T extends EventMap> = string & keyof T; type EventReceiver<T> = (params: T) => void; interface Emitter<T extends EventMap&g ...

Modify the database entry only if the user manually changes it, or temporarily pause specific subscriptions if the value is altered programmatically

After a change in the viewmodel, I want to immediately update the value on the server. class OrderLine { itemCode: KnockoutObservable<string>; itemName: KnockoutObservable<string>; constructor(code: string, name: string) { ...

A helpful guide on showcasing error messages at the top of a form in Angular using reactive forms

I have a Validation summary component that is designed to fetch an ngForm, but it is currently unable to subscribe to status changes or value changes and display the summary of error messages. export class CustomValidationSummaryComponent implements OnIni ...

Unable to locate element in the DOM using XPath

Having trouble retrieving an element from the DOM using XPath <input bsdatepicker="" class="form-control font-size-normal ng-untouched ng-pristine ng-valid" id="endDate" name="endDate" placement="top" type="text"> The value of the element is not p ...

Implementing a builder pattern with @Ngrx/Store

Feeling a bit uncertain... I'm wondering if it's suitable, awesome or not advisable to employ a builder pattern to retrieve API response and then apply the builder pattern on that response before storing it in @ngrx/store? And later on when acces ...

Nest is unable to resolve the dependencies of the ItemsService. Ensure that the required argument at index [0] is present within the AppModule context

After following the Nest JS Crash tutorial from a Youtube Link, I encountered an error when importing an interface in the service. Nest seems unable to resolve dependencies of the ItemsService. It's important to ensure that the argument at index [0 ...