在Angular项目中,有几种方法可以保持变量的最佳方式。以下是其中一种方法的代码示例:
// my-data.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyDataService {
private myVariable: string;
constructor() { }
setVariable(value: string) {
this.myVariable = value;
}
getVariable() {
return this.myVariable;
}
}
在组件中使用该服务:
// app.component.ts
import { Component } from '@angular/core';
import { MyDataService } from './my-data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private myDataService: MyDataService) { }
saveVariable(value: string) {
this.myDataService.setVariable(value);
}
getVariable() {
return this.myDataService.getVariable();
}
}
// my-data.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MyDataService {
private myVariable = new BehaviorSubject('');
setVariable(value: string) {
this.myVariable.next(value);
}
getVariable() {
return this.myVariable.asObservable();
}
}
在组件中使用该服务:
// app.component.ts
import { Component } from '@angular/core';
import { MyDataService } from './my-data.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myVariable$: Observable;
constructor(private myDataService: MyDataService) {
this.myVariable$ = this.myDataService.getVariable();
}
saveVariable(value: string) {
this.myDataService.setVariable(value);
}
}
这两种方法都可以在整个应用程序中保持变量的状态,并且可以从多个组件中访问和更新变量的值。