Angular 2.x 监听变量变化

13 浏览
0 Comments

Angular 2.x 监听变量变化

我正在从angular 1.x迁移到2.x,但我的大脑仍然在使用angular 1.x,对于愚蠢的问题我表示抱歉。

我需要在一个scope变量组件属性变化时执行一些操作。我找到了一个解决方案,但我认为应该有更好的解决方案。

export class MyApp {
    router: Router;
    location: Location;
    fixed: boolean = true;
    private set isFixed(value:boolean) {
        this.fixed = value;
        //TODO: 在这里查看
        console.log('isFixed变化', value);
    }
    private get isFixed():boolean {
        return this.fixed;
    }
    constructor(router: Router, location: Location) {
        this.router = router;
        this.location = location;
    }
}

看一下console.log('isFixed变化', value);这行。这就是我需要的,而且它已经起作用了。但我通过声明gettersetter来实现的,但是是否有更好的解决方案来监听变量呢?就像在angular 1.x中的$scope.$watch一样?

我认为我的组件代码应该是这样的

export class MyApp {
    router: Router;
    location: Location;
    isFixed: boolean = true;
    //TODO: 监听isFixed变化的代码 {
        console.log('isFixed变化', value);
    // }
    constructor(router: Router, location: Location) {
        this.router = router;
        this.location = location;
    }
}

0
0 Comments

Angular 2.x的变量监视问题的原因是希望通过服务自动获取更新后的值。解决方法如下:

首先,在服务文件中引入相关的依赖包,并创建一个BehaviorSubject对象来存储变量的初始值。然后,通过asObservable()方法将其转换为可观察对象。在更新变量值的方法中,通过next()方法来更新值,并在控制台输出变量变化的信息。

其次,在任何组件中(可以在ngOnInit或其他任何地方)可以通过订阅这个可观察对象来获取变量的值。这样的话,当变量值更新时,订阅的回调函数会自动执行。

最后,可以通过调用服务的方法来更新或设置变量的新值。只需要传入新的布尔值作为参数即可。

希望这个解决方法对你有用。

0
0 Comments

Angular 2.x watching for variable change

在Angular 2.x中,有时候我们需要在一个类中观察一个变量的变化。下面是一个解决这个问题的方法。

解决方法:

首先,可以使用BehaviorSubject,它允许我们为感兴趣的属性设置一个初始值,然后在注入该服务的任何地方订阅对该属性的更改。

例如:

export class SomeService {
  private fixed = new BehaviorSubject(true); // true是你的初始值
  fixed$ = this.fixed.asObservable();
  private set isFixed(value: boolean) {
    this.fixed.next(value);
    console.log('isFixed changed', value);
  }
  private get isFixed():boolean {
    return this.fixed.getValue()
  }
  constructor(router: Router, location: Location) {
    this.router = router;
    this.location = location;
  }
}

然后,在一个感兴趣的类(例如组件)中,可以订阅fixed值的变化:

export class ObservingComponent {
  isFixed: boolean;
  subscription: Subscription;
  constructor(private someService: SomeService) {}
  ngOnInit() {
    this.subscription = this.someService.fixed$
      .subscribe(fixed => this.isFixed = fixed)
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

更新值的方法如下:

export class Navigation {
  constructor(private someService: SomeService) {}
  selectedNavItem(item: number) {
    this.someService.isFixed(true);
  }
}

以上就是解决Angular 2.x观察变量变化的方法。

0
0 Comments

Angular 2.x watching for variable change

在Angular 2.x中,如果你想要监测一个变量的变化,你可以实现OnChanges接口并实现ngOnChanges()方法。这个方法会在组件的输入或输出绑定值发生变化时被调用。

Dart代码示例:

bool fixed;

void ngOnChanges(Map changes) {

print(changes);

}

如果你想要对普通属性进行监测,可以将属性定义为getter/setter,并在setter中触发你的代码。

但是,似乎这种方式并不自然,属性本身不应该关心其他人对其变化的反应。我之前使用过Ember框架,在那里创建观察者非常简单。

然而,Angular并没有为这种用例提供特殊支持。

0