Angular-无法使用.subsribe将json数据存储在变量中

时间:2019-03-28 10:55:41

标签: angular typescript

我遇到的问题是我无法在执行Post请求时将数据存储在变量中……我如何将所需的特定数据存储在变量中?

我发出了一个Post请求,在该请求中我要取回数据,但是它根本没有将我想要的数据存储在变量中。

我的代码:

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




  }
}
import { Component, OnInit } from '@angular/core';
import { TranslateService } from '../translate.service';
import { TranslatedText, Translations } from '../TranslatedText';
import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';
import { TmplAstText } from '@angular/compiler';
@Component({
  selector: 'app-translate',
  templateUrl: './translate.component.html',
  styleUrls: ['./translate.component.css']
})

export class TranslateComponent implements OnInit {

  tText: Object[];


  constructor(private translateService: TranslateService) { }

  ngOnInit() {
  }

  textTranslation = "This text is about to get translated";



  text3: TranslatedText = new TranslatedText();



  getTranslation(textToTranslate: string) {

     this.translateService.getTranslation(textToTranslate).subscribe(
      data => {
       this.text3.translations = data.translations;
        console.log('Data that I get',data)
      });

      console.log(this.text3);


  }

}

json我回来了:

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

export class DetectedLanguage {
    language: string;
    score: number;
}
export class Translations {

    text: string;
    to: string;

}


<p>
  translate works!
</p>

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

<!-- <div *ngIf="text3">
  <h1>{{text2}}</h1>
</div> -->

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


<button (click)="getTranslation(text.value)">TRANSLATE (gives Json back) </button>

我希望在this.text3.translations中存储data.translations的值,但是它说data.translations是未定义的。我调试并查看它是否具有值。

https://gyazo.com/1bf9f7f3d9fe491a479d1d837f32428a

1 个答案:

答案 0 :(得分:0)

您能否在下面第二个问题中将以下代码格式化为

getTranslation(textToTranslate: string) {

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

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

您还可以从

更改服务中的以下代码吗?
let result = this.http.post<TranslatedText>('https://localhost:5001/api/translate/', body, options);
    console.log("result", result);
    return result

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

要显示值,您可以执行此操作

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

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