Luan Tominaga
Luan Tominaga

Reputation: 1

How to change variable value in service.ts angular?

I'm pretty new as a programmer and with the angular framework too, so the question can be very obvious.

I have a service.ts file that runs CRUD with firebase and inside Firebase I am performing a filter that depends on the value of the variable "this.machine". Depending on the machine name a filter is performed and shows data only from this machine.

This is a part of the code:

@Injectable()
export class CrudCadastroService {
  public machineList: Machine[];
  cadastroList: AngularFireList<any>;
  selectedCadastro: CadastroModal = new CadastroModal();
  machine: string;

  constructor(
    private firebase :AngularFireDatabase
   ) { }

  getData(){
    this.cadastroList = this.firebase.list('cadastros', ref => ref.orderByChild('machine').equalTo(**this.machine**));  
    return this.cadastroList;
  }

I have another service.ts that push list from Firebase database and I'm using in component.ts.

In this file componete.ts I get the value of this variable.

  changeShape(shape) {
   //Get name machine value
   //I want to use this variable **machine** into service.ts
    let machine= shape.value;
    console.log(machine) //name of machine
  }

This is my html

<div class="form-group">
  <select name="machine" #machine="ngModel [(ngModel)]="cadastroService.selectedCadastro.machine"
  (change)="changeShape($event.target)" >
    <option *ngFor="let machine of machineList"
    >{{machine.name}}</option>
  </select>
</div>

My question is, can I change the value of this.machine in the service.ts file? Is there any different way of doing this logic?

Upvotes: 0

Views: 1559

Answers (2)

user2590928
user2590928

Reputation: 176

In typescript, accessors are public by default so if your CrudCadastroService is injected in your component as "crudCastroService" you could change its value in component.ts with just

this.crudCastroService.machine = 'newName';

Upvotes: 0

Ishant Gaurav
Ishant Gaurav

Reputation: 1203

You can create a setter method in service.ts and from component.ts before calling for getting the list for that machine , call the setter method to machine value .

Upvotes: 1

Related Questions