简体   繁体   English

如何在角度订阅服务后全局分配一个值

[英]How to assign a value globally after a service subscription in angular

Is there any way to assign a value globally outside of a method in my app component?有没有办法在我的应用程序组件中的方法之外全局分配一个值?

My service looks like this:我的服务看起来像这样:

import { NumberInput } from '@angular/cdk/coercion';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Candidato } from "../interfaces/candidato";
import { Cuestionario } from '../interfaces/cuestionario';
import { Respuesta } from '../interfaces/Respuesta';
import { Verdaderos } from '../interfaces/verdaderos';
@Injectable({
  providedIn: 'root'
})
export class CandidateService {

  url="http://localhost:3000/api"

  constructor(private http:HttpClient) { }



  getPersona(ID:Number):Observable<Candidato[]>{
    return this.http.get<Candidato[]>(this.url + "/persona/searchrh/"+ID)
  }

  deletePersona(ID_RH:Number,ID:Number){
    return this.http.delete<Respuesta>(this.url+"/persona/deleteRH/"+ID_RH+"/"+ID)
  }

  getCandidato(ID:Number):Observable<Candidato>{
    return this.http.get<Candidato>(this.url + "/persona/search/"+ID)
  }

  getCuestionarioRespuestas(ID:Number):Observable<Verdaderos[]>{
    return this.http.get<Verdaderos[]>(this.url + "/cuestionario/"+ID)
  }
}

With interface Verdaderos looking like this:界面 Verdaderos 看起来像这样:

export interface Verdaderos{
    Pregunta: number;
}

What I get from the service is an object array containing certain IDs belonging to all the "answers" with certain response, the issue here is I need to count them in order to sort them properly.我从服务中得到的是一个对象数组,其中包含属于具有特定响应的所有“答案”的特定 ID,这里的问题是我需要对它们进行计数以便对它们进行正确排序。 My method looks like this, with M,N and P being global variables equal to zero.我的方法看起来像这样,其中 M、N 和 P 是全局变量,等于零。

getRespuestasCandidato(ID: Number) {
    this.Persona.getCuestionarioRespuestas(ID).subscribe((data:Verdaderos[]) =>{
      this.conteo = data;
      this.numbers = this.conteo.map(x => x.ID_Pregunta);
      console.log(this.numbers)

      const N2 = this.N1.filter(x => this.numbers.includes(x));
      const countN2 = N2.length;
      console.log(countN2)

      const M2 = this.M1.filter(x => this.numbers.includes(x));
      const countM2 = M2.length;
      console.log(countM2)

      const P2 = this.P1.filter(x => this.numbers.includes(x));
      const countP2 = P2.length;
      console.log(countM2)
      this.N = countN2;
      this.M = countM2;
      this.P = countP2
    })
  }

Printing any variable avia console naturally gets me the value I'm looking for, but I haven't been able to assign those values to the global variable in order to plot them using ngx-charts通过控制台打印任何变量自然会得到我正在寻找的值,但我无法将这些值分配给全局变量以便使用 ngx-charts 绘制它们

NE = 100 - this.N- this.M- this.P

single = [
    {
      "name": "Narcisismo",
      "value": this.N    },
    {
      "name": "Maquiavelismo",
      "value": this.M
    },
    {
      "name": "Psicopatia",
      "value": this.P
    },
    {
      "name": "No evaluado",
      "value": this.NE
    }
  ];

Naturally, single is declared before the constructor, and that's what I need to render a pie chart with the correct data自然地,在构造函数之前声明了 single,这就是我需要用正确的数据渲染饼图

Is there something wrong with my logic or my syntax?我的逻辑或语法有问题吗? I'm calling the method this.getRespuestasCandidato(this.ID);我正在调用方法 this.getRespuestasCandidato(this.ID); "inside" AfterViewInit, but even then, if I change the lifecycle, I haven't been able to get the values I need for my chart “内部”AfterViewInit,但即便如此,如果我更改生命周期,我也无法获得图表所需的值

Here's the html:这是 html:

<div class="wrapperuser">
    <div class="container-sm grafico">
        <ngx-charts-pie-chart
        [view]="view"
        [results]="single"
        [gradient]="gradient"
        [legend]="showLegend"
        [labels]="showLabels"
        [doughnut]="isDoughnut">
        </ngx-charts-pie-chart>
    </div>
</div>

On option is to use pipeable operator map to transform the stream into needed data and use the async pipe operator in the template.可选的是使用可管道运算符map将流转换为所需的数据,并在模板中使用async管道运算符。 This takes care of subscribing and unsubscribing.这会处理订阅和取消订阅。

single$: Observable<ISingleInterface> = of()

ngOnInit() {
    this.single$ = this.Persona.getCuestionarioRespuestas(ID).pipe(
        map((data: Verdaderos[]) => {
            // calculate `single` as in question
            return single;
        }),
        // the following may be required depending on if ngx-charts needs this
        // startWith(defaultSingleValue)
    );
}
<div class="wrapperuser">
    <div class="container-sm grafico">
        <ngx-charts-pie-chart
        [view]="view"
        [results]="single$ | async" <---------------- async pipe subscribes and passes value
        [gradient]="gradient"
        [legend]="showLegend"
        [labels]="showLabels"
        [doughnut]="isDoughnut">
        </ngx-charts-pie-chart>
    </div>
</div>

If you don't include a default via startWith, single$ | async如果您不通过 startWith 包含默认值,则single$ | async single$ | async will initially pass null and then the data will be pass to the component. single$ | async最初将传递 null,然后将数据传递给组件。 You may want to guard fully against this with a wrapping <div *ngIf="(single$ | async) as single">您可能希望通过包装来完全防止这种情况<div *ngIf="(single$ | async) as single">

An alternative is to manually subscribe within the subscribe assign to variable on the component this.single = // calc but the same thing will happen.另一种方法是在订阅中手动订阅分配给组件上的变量this.single = // calc但同样的事情会发生。 It'll begin with an an initial value that updates once the data is received.它将以一个初始值开始,该初始值会在收到数据后更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM