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.