I need to export a variable from one typescript to another, but the variable does not get the value I need

Asked

Viewed 558 times

1

I need to export the language variable of a ts to another, however, the variable (language) that is being exported does not present the value that I want to export.

I tried to put the export in some line inside the same part as the variable, also I tried to create a new variable to be exported that copies the value of the variable I want to export.

export class IdiomasPage implements OnInit {
  idioma = `br`;


  constructor() { 

  }


  ngOnInit() {

  }


  idiomabr(){
    this.idioma = `br`
    console.log(this.idioma)
  }

  idiomaus(){
    this.idioma = `us`
    console.log(this.idioma)
  }


}

export var idioma;

I need the language variable in export to have the same value as the language variable in the functions.

  • It won’t work, Fabio. First language is a property of the Languagespage class, it is not defined in the scope that export has access to, so it must be returning undefined. You should return the class and create an instance of it where you need to call this value,.

  • obg, I’ll try to apply

1 answer

1

You can use this variable as a observable so you can access the variable value anywhere in the application. Provide these variable access and value exchange methods via a service.

first create the service :

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

@Injectable({providedIn: 'root'})

export class IdiomasPageService {

// cria um novo behaviorSubject do tipo string.
private idiomaSubject = new BehaviorSubject<String>('br');

constructor() {}

// esse método retorna o subject onde você acessará o valor da sua variável idioma
getIdioma() {
    return this.idiomaSubject.asObservable();
}

emitNewValue(novoIdioma: string) {
    this.idiomaSubject.next(novoIdioma);
}

}

Then in your Languagespage class take an instance of the object using the service:

export class IdiomasPage implements OnInit {

private idioma = Observable<String>;

constructor(private idiomasPageService: IdiomasPageService) {}

ngOnInit() {
    //por padrão o primeiro valor de idioma é 'br', valor passado ao instanciar o behaviorSubject no serviço
    this.idioma = this.idiomasPageService.getIdioma();
}

alterarIdioma() {
    //alterando o valor de idioma na aplicação toda para 'pt' e depois 'en'
    this.idiomasPageService.emitNewValue('pt');
    this.idiomasPageService.emitNewValue('en');
}

}


now anywhere in your application you can access and change the language value using the service :).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.