angular - 无法以角度将值传递给组件
问题描述
我想将一个服务的值传递给另一个服务。
我将 FirstService 中的值设置为可观察的,而 SecondService 订阅了该值。一旦值被改变,服务就会做出反应。
“first.service.ts”
export class FirstService extends Service {
private readonly firstValue =
new BehaviorSubject<string>('');
getFirstValue(): Observable<string> {
return this.firstValue;
}
setFirstValue(value: string) {
this.firstValue.next(value);
}
}
“第二个.service.ts”
export class SecondService extends Service {
private secondValue: string;
constructor(http: HttpClient, private firstService: FirstService ) {
super(http);
firstService.getFirstValue().subscribe(
(val) => {
this.secondValue = val;
}
);
}
}
但是每次输入SecondService的Component的url,Service(SecondService)都会被重构,它订阅的Service(FirstService)也会被初始化。所以我失去了我之前设定的价值。
我应该怎么做才能将值传递给服务。非常感谢!
解决方案
@Injectable({
providedIn: 'root',
})
export class FirstService extends Service {
firstValue = new BehaviorSubject<string>('');
$firstValue = this.firstValue.asObservable();
setFirstValue(value: string) {
this.firstValue.next(value);
}
}
并删除模块和组件中对第一个服务的任何引用。在第二次服务中:
firstService.firstValue$.subscribe(val => this.secondValue = val);
如果你不希望你的第一个服务每次都被初始化,你应该把root
参数放在注入器中。
从'@angular/core'导入{可注射};
@Injectable({
providedIn: 'root',
})
export class UserService {
}
更多信息:https ://angular.io/guide/singleton-services
更多信息:https ://indepth.dev/angulars-root-and-any-provider-scopes/
推荐阅读
- python - sklearn learning_curve 和 StandardScaler
- django - 基类视图上的 Django URL 自定义参数
- sql - Oracle:将两行值合并为具有新列名的一行
- asp.net - Asp.net core 2.0部署海量dll
- python - 如何在 pandas df 上使用这个工作正则表达式(re)来删除多余的非数字字符,星号(*)?
- python - 为什么我会得到无效的 else 语法
- java - 在单个方法中重用连接对象
- git - 从上游远程分支合并到本地远程分支
- javascript - 如何在 jasmine-marble 中创建 Observable 计时器测试?
- node.js - AWS lambda 函数错误 - 无法导入模块“索引”:错误