如何在 service.ts 角度中更改变量值?



作为一名程序员,我是一个新手,对角度框架也很陌生,所以这个问题可能非常明显。

我有一个 service.ts 文件,该文件使用 firebase 运行 CRUD,在 Firebase 内部,我正在执行一个取决于变量">this.machine"值的过滤器。根据计算机名称,将执行筛选器,并仅显示来自此计算机的数据。

这是代码的一部分:

@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;
}

我有另一个从Firebase数据库推送列表的服务.ts,我在component.ts中使用。

在这个文件中 componete.ts 我得到了这个变量的值。

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
}

这是我的网页

<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>

我的问题是,我可以在service.ts文件中更改this.machine的值吗?有没有不同的方法来做这个逻辑?

您可以在 service.ts 和 component.ts 中创建 setter 方法,然后再调用 获取该机器的列表 ,调用 setter 方法到机器值。

在 typescript 中,访问器默认是公共的,所以如果你的 CrudCadastroService 作为"crudCastroService"注入到你的组件中,你可以在 component.ts 中更改它的值,只需

this.crudCastroService.machine = 'newName';

最新更新