Storing JSON data in a variable using .subscribe is not possible in Angular

Currently, I am encountering an issue where I cannot successfully store the specific data obtained from a Post request into a variable. How can I resolve this and ensure that only the desired data is stored?

After making a Post request and receiving back data, I am facing difficulties in storing the relevant information into a variable.

The Code:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { TranslatedText } from './TranslatedText';
import { v4 as uuid } from 'uuid';
import { resource } from 'selenium-webdriver/http';
import { catchError, map, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class TranslateService {

 constructor(private http: HttpClient) { }

 getTranslation(textToTranslate: string): Observable<TranslatedText> {
   const options = { headers: { 'Content-Type': 'application/json' } };
   let body = JSON.stringify({ Text: textToTranslate });
   console.log("json ", body);

   let result = this.http.post<TranslatedText>('https://localhost:5001/api/translate/', body, options);
   console.log("result", result);
   return result
 }
}

I encountered an issue with storing the received translation data. The expected values were not being stored in the specified variable (this.text3.translations), even though the data was clearly defined. Here's what happened:

[
    {
        "detectedLanguage": {
            "language": "en",
            "score": 1
        },
        "translations": [
            {
                "text": "Hello World!",
                "to": "de"
            }
        ]
    }
]
export class TranslatedText {
 detectedLanguage: DetectedLanguage;
 translations: Translations[];
}

export class DetectedLanguage {
 language: string;
 score: number;
}
export class Translations {
 text: string;
 to: string;
}
<p>The translation process is functioning correctly!</p>

<label>Translate</label>
<input #text type="text" value="{{textTranslation}}"> <br>

<div *ngIf="text3.translations[0].text.length">
{{text3.translations[0].text}}
</div>

<button (click)="getTranslation(text.value)">TRANSLATE (returns Json response) </button>

I anticipated that the values from data.translations would be stored within this.text3.translations, but encountered issues where it stated that data.translations was undefined. Upon further investigation, I verified that the values were indeed present.

https://gyazo.com/1bf9f7f3d9fe491a479d1d837f32428a

Answer №1

Could you kindly reformat the code provided in the second part of your question?

getTranslation(textToTranslate: string) {

     this.translateService.getTranslation(textToTranslate).subscribe(
          data => {
           this.text3.translations = data.translations;
            console.log('Received Data:',data)

            console.log(this.text3); // <--- Verify this value
          });
  }

Additionally, please make the following modification in the service code:

return this.http.post<TranslatedText>('https://localhost:5001/api/translate/', body, options);

You can display the value using either of these approaches:

<div *ngIf="text3 && text3.translations && text3.translations[0].text.length">
 {{text3.translations[0].text}}
</div>

or

<div *ngIf="text3?.translations[0]?.text?.length">
 {{text3.translations[0].text}}
</div>

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

What is the best way to showcase information in Angular?

I am facing an issue where my cards are not displaying data from the database, they appear empty. Can anyone provide a solution to help me fix this problem? Below is the output I am getting, with the empty cards that I want to populate with data. https:// ...

Combining the output of two Observables through the CombineLatest method to generate a

I possess two separate collections of information: Data Model: taxControlReference [ { "providerId": "HE", "taxTables": { "STAT": [ 1 ] } }, ...

``Using backticks to denote HTML syntax - Leveraging Google Charts to create

Has anyone found a way to incorporate HTML in ticks within a Google chart? I am attempting to insert a weather icon from This is my current attempt: const dailyData = new google.visualization.DataTable(); dailyData.addColumn('timeofday' ...

Unable to translate text on the loading page

Encountering a peculiar issue with the translate service. Here's how I set it up: export class AppComponent implements OnInit { constructor( private translateService: TranslateService, angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics ...

Changing the type of value in a React select onChange

<Select options={options} value={selectedBusinessList} isMulti placeholder="Select Business" onChange={(value: any) => setSelectedBusinessList(value)} onInputChange={query => { if ...

Angular2 display user's activity status on every individual page

How can I implement visitor status tracking for every page in angular2? I have a jwt based authentication system in place that is working correctly, but now I need to ensure that the visitor's login status is checked on each route. Here is an example ...

Angular authentication guard does not redirect properly after returning a Promise<UrlTree>

My authentication guard is set up to control access to the /sign-in and /verify-email routes, allowing only users who are not logged in or have not verified their email: export const signInGuard: CanActivateFn = (activatedRouteSnapshot: ActivatedRouteSnap ...

Navigating to the HomePage using the nebular auth/login library with the login() function: A step-by-step guide

After setting up my Angular Project and installing the nebular library, I am working on creating 3 pages: Login, Register, and Home. I have successfully created the login and register pages using NbLoginComponent and NbRegisterComponent. Now, my goal is to ...

Angular 6's HttpClient fails to manage HttpHeaders as anticipated

Currently, I am in the process of upgrading my app from Angular 4 to Angular 6. I understand the importance of using an Interceptor, although I am hesitant to introduce more breaking changes than necessary. Lately, I've been delving into the details ...

Unable to submit a post on Ionic 3 platform

I've been attempting to make a POST request using HttpClient Angular to communicate with a server, but I've encountered an error in my code: File: *.ts import { HttpClient } from '@angular/common/http'; constructor(public http: Http ...

Is there a way to create a new perspective for Ion-Popover?

Looking for a solution: <ion-grid *ngIf="headerService.showSearch()"> <ion-row id="searchbar" class="main-searchbar ion-align-items-center"> <ion-col size="11"> ...

New Entry failing to appear in table after new record is inserted in CRUD Angular application

Working with Angular 13, I developed a basic CRUD application for managing employee data. Upon submitting new information, the createEmployee() service is executed and the data is displayed in the console. However, sometimes the newly created entry does no ...

Improving the URL structure in Angular 8 with ngx-extended-pdf-viewer

How to prevent ngx-extended-pdf-viewer from removing # in Angular URL I have integrated "ngx-extended-pdf-viewer": "^7.3.2", and "zone.js": "~0.10.3" I need to retain the # in my URL: @NgModule({ imports: [RouterModule.forRoot(routes,{useHash: true,})] ...

Choose several checkboxes from the dropdown menu

After clicking the dropdown, I want to select multiple checkboxes instead of just one. I have tried using the prevent default method but it did not work. Beginner concept ...

After the rendering process, the React Component member goes back to a state of

One issue I encountered is related to a component that utilizes a separate client for making HTTP requests. Specifically, when trying to use the client within a click event handler, the call to this.client.getChannel() fails due to this.client being undefi ...

The class-transformer malfunctioning: The transformation function is not being executed

I am facing an issue with implementing class-transformer in my codebase, despite using type-graphql and @typegoose/typegoose libraries. Below is the snippet of my code: Custom Decorator import { Transform } from 'class-transformer'; export func ...

Why is my React component not being updated with Routes?

I'm new to using react-router and I'm struggling with it for the first time. Here is the code snippet: App.tsx import React from 'react'; logo = require('./logo.svg'); const { BrowserRouter as Router, Link, Route } = require ...

"Revolutionize your date and time selection with the dynamically updating columns

I am in need of a time selection feature where users can choose both hours and minutes. Each hour will have its own set of minutes, and the data structure should look like this: [ { hour: 1, minutes: [0, 15, 30], }, { hour: 4, minut ...

What is the correct way to incorporate service within a component function?

Here's how I'm implementing an inline input edit component: <app-inline-input-edit [label]="'Manufacturer'" [required]="true" [(ngModel)]="ctrlTypes.manufacturer" name="manufacturer" [changed]="onChange"> ...

Guide on populating text boxes in a form automatically using ngFor?

As a beginner Angular developer, I am looking to automatically fill in text boxes in a form, specifically 10 text boxes (10 rows) using the ngFor directive. In my research on ngFor examples, I have noticed that most of them focus on populating a list base ...