从Angular中的事件订阅中更新变量

时间:2018-06-28 11:35:46

标签: angular rxjs

我正在尝试从事件订阅中更新变量。变量已在内部更新,但尚未在外部更新。

import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { pairwise, filter } from 'rxjs/operators';

@Component({
  selector: 'elephant-component',
  templateUrl: './elephant.component.html',
})
export class ElephantComponent  {

routedFromTraining: boolean = false;

constructor(private router: Router) {
  this.router.events
   .pipe(filter(e => e instanceof NavigationEnd), pairwise())
   .subscribe((event) => {
     if (event[0]['url'] == '/trainings') {
       this.routedFromTraining = true;
       // this.routedFromTraining is true
     }
   });
  // this.routedFromTraining is false
 }
}

1 个答案:

答案 0 :(得分:0)

因为这是异步操作,并且您正在尝试同步观察更改!您可能最初将其设置为false。如果要检查从subscribe()获得的价值,则必须之后检查subscribe()调用是否已完成。而是这样做:

this.router.events
   .pipe(filter(e => e instanceof NavigationEnd), pairwise())
   .subscribe((event) => {
     if (event[0]['url'] == '/trainings') {
       this.routedFromTraining = true;
       // this.routedFromTraining is true
     }
    }, 
    (er) => console.log(err),
    () => console.log(this.routedFromTraining)   // this is an asynchronous operation so correct output will be displayed here
   );
  // this.routedFromTraining is false
 }