Как экспортировать переменную внутри класса и функции в другой компонент в Angular? - PullRequest
0 голосов
/ 19 января 2020

У меня есть компонент с именем flow.component.ts, например:

var rsi_result: number[];

@Component({
  selector: 'flow-home',
  templateUrl: './flow.component.html',
  styleUrls: ['./flow.component.scss'],
  host: {
    '[@flyInOut]': 'true',
    'style': 'display: block;'
  },
  animations: [
    flyInOut(),
    expand()
  ]
})
export class FlowComponent implements AfterViewInit {

  setRsi(selectedValue){
    console.log('The RSI period is:' , selectedValue);
    periodd = selectedValue;
    this.label2 = ' نام اندیکاتور:  RSI';
    this.label3 = ' دوره زمانی: ' + periodd + 'روزه';
    rsi_result = rsi({period: periodd, values: pricess});
    console.log('The RSI result is:' ,  rsi_result);
  }

}

export const RSI_RESULT = rsi_result;

Код работает хорошо, и я вижу результат этой строки кода в моей консоли console.log('The RSI result is:' , rsi_result);, но, похоже, export Линия вне класса не работает, и я не могу использовать RSI_RESULT в других компонентах и ​​получить undefined RSI_RESULT сообщение об ошибке! Также, когда я пишу rsi_result или RSI_RESULT в консоли, я получаю ту же неопределенную ошибку!

Как это возможно, когда эта строка кода console.log('The RSI result is:' , rsi_result); работает хорошо, и я вижу rsi_result в консоли, но когда я набираю его вручную, я получаю неопределенное сообщение об ошибке?

EDITL

Я пытался создать службу с именем ngx.service с таким содержанием:

import { Injectable } from '@angular/core';

var RSI_RESULT: number[];
var MACD_RESULT: number[];

@Injectable({
  providedIn: 'root'
})
export class NgxService {

getRsiResult(){ 

  return (RSI_RESULT);
}  

getMacdResult(){ 
  return (MACD_RESULT);

}

  constructor() { }

}

Затем отредактировал приведенный выше код так:

export class FlowComponent implements AfterViewInit {

  macd_result: number[];
  rsi_result: number[];
  constructor(private dialog: MatDialog, private ngxService:NgxService) {
  }
  setRsi(selectedValue){
    console.log('The RSI period is:' , selectedValue);
    periodd = selectedValue;
    this.label2 = ' نام اندیکاتور:  RSI';
    this.label3 = ' دوره زمانی: ' + periodd + 'روزه';
    this.rsi_result = rsi({period: periodd, values: pricess});
    console.log('The RSI result is:' ,  this.rsi_result);
  }

}

Но когда я хочу использовать rsi_result в следующем компоненте с именем ngx-charts Я получаю ту же ошибку, что и раньше:

import { Component, OnInit } from '@angular/core';
import {MatDialog, MatDialogRef} from '@angular/material';
import { NewsComponent } from '../news/news.component';
import {NgxService} from '../services/ngx.service';
import { Mellat , Khodro, Shepna} from '../shared/stock_inf';


@Component({
  selector: 'app-ngx-charts',
  templateUrl: './ngx-charts.component.html',
  styleUrls: ['./ngx-charts.component.scss']
})



export class NgxChartsComponent implements OnInit {

  rsi_result: number[];
  macd_result: number[];

  constructor(public dialogRef: MatDialogRef<NgxChartsComponent> ,
     private ngxService: NgxService) { }

     ngOnInit() {
      this.rsi_result = this.ngxService.getRsiResult(); //.subscribe(RSI_RESULT => this.rsi_result = RSI_RESULT);
      this.macd_result = this.ngxService.getMacdResult(); //.subscribe(MACD_RESULT => this.macd_result = MACD_RESULT);

      console.log(this.rsi_result); 
    }

  // data goes here
public single = [
  {
    "name": " درصد سود",
    "value": 69
  },
  {
    "name": " درصد زیان",
    "value": 31
  },

];


 newArray = Mellat.map((e, i) => ({
  "name": (i + 1).toString(),
  "value": e,
}));

newArray2 = this.rsi_result.map((e, i) => ({
  "name": (i + 1).toString(),
  "value": e,
}));


public multi = [
  {
    "name": "Mellat",
    "series": this.newArray
  },

  {
    "name": "RSI",
    "series": this.newArray2
  }
];

//{name: (i + 1).toString(), value: e.toString()}



  view: any[];

  // options for the chart
  showXAxis = true;
  showYAxis = true;
  gradient = false;
  showLegend = true;
  showXAxisLabel = true;
  xAxisLabel = 'زمان';
  showYAxisLabel = true;
  yAxisLabel = 'قیمت';
  timeline = true;

  colorScheme = {
    domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA']
  };

  // line, area
  autoScale = true;

  //pie
  showLabels = true;
  explodeSlices = false;
  doughnut = false;


}

EDIT2:

Я снова просмотрел свой код и заметил, что должен удалить var RSI_RESULT: number[]; и MACD_RESULT: number[]; из моего приложения, а также замените this.rsi_result строк на this.ngxService.RSI_RESULT, когда мой ngx.service.ts файл выглядит следующим образом:

import { Injectable } from '@angular/core';
import {Observable, of} from 'rxjs';



@Injectable({
  providedIn: 'root'
})
export class NgxService {

RSI_RESULT: number[];
MACD_RESULT: number[];

getRsiResult(){ //: Observable<number[]>{

  return (this.RSI_RESULT);
}  

getMacdResult(){ //: Observable<number[]>{
  return (this.MACD_RESULT);

}

  constructor() { }

}

И теперь программа работает хорошо!

1 Ответ

1 голос
/ 19 января 2020

Вам нужно поместить ваш share info в службу и внедрить эту службу во все ваши компоненты.

export class FlowComponent implements AfterViewInit {

  constructor(private readonly myService: MyService){}

  setRsi(selectedValue){
    console.log('The RSI period is:' , selectedValue);
    periodd = selectedValue;
    this.label2 = ' نام اندیکاتور:  RSI';
    this.label3 = ' دوره زمانی: ' + periodd + 'روزه';
    this.myService.setRsi(rsi({period: periodd, values: pricess}));
    console.log('The RSI result is:' ,  rsi_result);
  }

}




// Other file
export class OtherComponent {

  constructor(private readonly myService: MyService){}

  getRsi(){
     return this.myService.getRsi();
   }

}
...