Angular 2.x观察变量变化

Arū*_*kas 26 javascript angular

我从角度1.x迁移到2.x但是我的大脑仍然在角度1.x中思考,所以对于愚蠢的问题感到遗憾.

我需要的是在我的一个范围变量组件属性发生变化时采取一些操作.我找到了解决方案,但我认为应该有更好的解决方案

export class MyApp {
    router: Router;
    location: Location;
    fixed: boolean = true;

    private set isFixed(value:boolean) {
        this.fixed = value;

        //TODO: look here
        console.log('isFixed changed', value);
    }

    private get isFixed():boolean {
        return this.fixed;
    }

    constructor(router: Router, location: Location) {
        this.router = router;
        this.location = location;
    }
}
Run Code Online (Sandbox Code Playgroud)

看看这条线console.log('isFixed changed', value);它是我需要的,它正在发挥作用.但我通过声明使得它gettersetter,但是是不是有更好的解决方案,以观察变量?像角度1.x一样$scope.$watch

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

export class MyApp {
    router: Router;
    location: Location;
    isFixed: boolean = true;

    //TODO: $watch for isFixed change {
        console.log('isFixed changed', value);
    // }

    constructor(router: Router, location: Location) {
        this.router = router;
        this.location = location;
    }
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 19

您可能希望实现该OnChanges接口并实现该ngOnChanges()方法.只要其中一个组件输入或输出绑定值发生更改,就会调用此方法.另请参见https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

飞镖代码示例

  @Input() bool fixed;

  @override
  void ngOnChanges(Map<String, SimpleChange> changes) {
    print(changes);
  }
Run Code Online (Sandbox Code Playgroud)

  • @GünterZöchbauer*常规*属性的任何类似解决方案? (2认同)

a d*_*ren 18

你可能会发现这个回答是委托:Angular2中的EventEmitter或Observable很有用(为我工作).

基本上你可以使用a BehaviorSubject,它允许你为你感兴趣的属性设置初始值,然后在注入服务的任何地方订阅对该属性的更改.

例如,如果我正确理解你,就像这样:

export class SomeService {
  private fixed = new BehaviorSubject<boolean>(true); // true is your initial value
  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;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在对fixed值感兴趣的类(例如Component)中:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

更新价值:

export class Navigation {
  constructor(private someService: SomeService) {}

  selectedNavItem(item: number) {
    this.someService.isFixed(true);
  }
}
Run Code Online (Sandbox Code Playgroud)