首页 > 解决方案 > 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

我只是忽略了什么吗?或者这是错误的方法?期待您的回答!

编辑:我添加了一些控制台日志。不幸的是,没有一个答案能够解决我的问题。我希望有人仍然可以帮助我。

标签: angulartypescriptservicebehaviorsubject

解决方案


推荐阅读