在订阅中更改变量不会显示在数据绑定中

时间:2018-11-17 20:10:04

标签: javascript angular rxjs

我有2个变量currentPathEmptycurrentPathFill。两者都是字符串。

我正在订阅一个BehaviorSubject。主题更改后,我会收到通知,它会在控制台中打印正确的值。应当。

ngOnInit() {
    // Irrelevant to this quesiton
    this.exercise = this.workoutService.workout.exercises[this.index];

    this.currentPathEmpty = this.arrowUpPathEmptly;
    this.currentPathFill = this.arrowUpPathFill;

    this.workoutService.player.exerciseStateSubject.subscribe((state) => {
      if (state === 'Rest') {

      } else if (state === 'Positive') {
        this.currentPathEmpty = this.arrowUpPathEmptly;
        this.currentPathFill = this.arrowUpPathFill;
     } else if (state === 'Hold') {
        this.currentPathEmpty = this.rectPathEmpty;
        this.currentPathFill = this.rectPathFill;
      } else if (state === 'Negative') {
        this.currentPathEmpty = this.arrowDownPathEmpty;
        this.currentPathFill = this.arrowDownPathFill;
      }
      console.log(this.currentPathFill);
    });
}

但是,当我在HTML中执行此操作时

<h1>{{currentPathFill}}</h1>

该值不会显示,并且主题发生更改的机会也很大。这里有什么问题?为什么它会在控制台上打印出正确的值,但我无法将数据绑定到它?

2 个答案:

答案 0 :(得分:0)

添加let self = this;

 ngOnInit() {

     // Irrelevant to this quesiton
    this.exercise = this.workoutService.workout.exercises[this.index];
    this.currentPathEmpty = this.arrowUpPathEmptly;
    this.currentPathFill = this.arrowUpPathFill;

   let self = this;
try {
    this.workoutService.player.exerciseStateSubject.subscribe(
    function (state) {
    self.callMe(state);  <--- call a method
    },
    error => console.log('Getting Error :: ' + JSON.stringify(error)));
     } 
    catch (e) { console.error('Error :: ' + JSON.stringify(e)); }


     callMe(state){
     if (state === 'Rest') {

          } else if (state === 'Positive') {
            this.currentPathEmpty = this.arrowUpPathEmptly;
            this.currentPathFill = this.arrowUpPathFill;
         } else if (state === 'Hold') {
            this.currentPathEmpty = this.rectPathEmpty;
            this.currentPathFill = this.rectPathFill;
          } else if (state === 'Negative') {
            this.currentPathEmpty = this.arrowDownPathEmpty;
            this.currentPathFill = this.arrowDownPathFill;
          }
          console.log(this.currentPathFill);
        }


<h1 *ngIf="currentPathFill">{{currentPathFill}}</h1>

答案 1 :(得分:0)

好的,问题是这两个变量的

this.arrowUpPathEmptly
this.arrowUpPathFill;

值在OnInit()之后绑定 检查控制台中的日志顺序