angular - Angular - 为什么我的组件从服务中的 Observable 获得默认值,尽管它之前已经更改过?
问题描述
我已经设置了一个 Angular-Service,它获取一个 URL 参数并将其保存到一个 BehaviorSubject 变量中。
@Injectable({
providedIn: 'root'
})
export class ResultService {
private resultDefault = new BehaviorSubject<string>("0");
currentResult = this.resultDefault.asObservable();
constructor(private router: Router) {
this.router.events.subscribe(val => {
if (val instanceof RoutesRecognized) {
console.log("resultDefault was:", this.resultDefault.getValue());
this.resultDefault.next(val.state.root.firstChild.params.id);
console.log("resultDefault is:", this.resultDefault.getValue());
}
});
}
现在我想通过订阅 Observable 从组件访问这个变量。
constructor( private resultService: ResultService ) { }
ngOnInit() {
this.resultService.currentResult.subscribe(data => {
console.log("Component gets:", data);
this.resultID = data;
});
}
但是,我得到的是默认值(“0”),尽管该变量已在服务的构造函数中更改。
这是控制台输出的内容,按以下顺序:
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
resultDefault was: 0
resultDefault is: 3
Component gets: 0
我只是忽略了什么吗?或者这是错误的方法?期待您的回答!
编辑:我添加了一些控制台日志。不幸的是,没有一个答案能够解决我的问题。我希望有人仍然可以帮助我。
解决方案
推荐阅读
- r - R - geom_point - 用于图例的分组
- python - Python - Scrapy splash 无法呈现此页面
- sql-server - Linux 上的 BCP 实用程序:NativeError = 18456 错误 = [unixODBC][Microsoft][ODBC Driver 17 for SQL Server][SQL Server]用户登录失败
- java - Firebase 服务帐户未读取
- coldfusion - 冷融合9:查询的查询显示没有结果
- sql - 如何更正 BAT 文件中的 Select Spool
- python - 使用逻辑运算符“not”的 While 循环说明
- c - 为什么修改 *int_one 的内存不会改变 *int_two 的内存值?
- python - 为什么我在列表理解 (Python) 中收到 NameError?
- node.js - 为给定主题的新消费者组设置初始“当前偏移量”和“滞后”