Javascript Angular 2.x 观察变量变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34434057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:19:54  来源:igfitidea点击:

Angular 2.x watching for variable change

javascriptangular

提问by Arūnas Smaliukas

I'm migrating from angular 1.x to 2.x but my brains still think in angular 1.x so sorry for silly questions.

我正在从 angular 1.x 迁移到 2.x,但我的大脑仍然在 angular 1.x 中思考,对于愚蠢的问题很抱歉。

What I need is to take some action when one of my scope variablescomponent properties changes. I found a solution but I think there should be better solution

当我的范围变量组件属性之一发生变化时,我需要采取一些措施。我找到了解决方案,但我认为应该有更好的解决方案

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;
    }
}

Look at the line console.log('isFixed changed', value);It's what I need and it's working. But I made it by declaring getterand setter, but isn't there a better solution to watch variables? Like in angular 1.x was $scope.$watch?

看看这条线console.log('isFixed changed', value);这是我需要的,它正在工作。但是我通过声明getterand 实现了它setter,但是没有更好的解决方案来观察变量吗?就像在 angular 1.x 中一样$scope.$watch

I think my component code should look like

我认为我的组件代码应该看起来像

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;
    }
}

采纳答案by Günter Z?chbauer

You might want to implement the OnChangesinterface and implement the ngOnChanges()method. This method is called whenever one of the components input or output binding value changes. See also https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

您可能想要实现OnChanges接口并实现ngOnChanges()方法。每当组件输入或输出绑定值之一发生变化时,就会调用此方法。另见https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

Dart code example

Dart 代码示例

  @Input() bool fixed;

  @override
  void ngOnChanges(Map<String, SimpleChange> changes) {
    print(changes);
  }

回答by a darren

You might find this answer to Delegation: EventEmitter or Observable in Angular2helpful (worked for me).

您可能会发现委托的答案:Angular2 中的 EventEmitter 或 Observable很有帮助(对我有用)。

Essentially you could use a BehaviorSubject, which allows you to set an initial value for the property you're interested in, then subscribe to changes to that property wherever that service is injected.

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

e.g. So, if I'm understanding you correctly, something like this:

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

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;
  }
}

Then in a class (e.g. Component) that's interested in the fixedvalue:

然后在对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();
  }
}

Update value:

更新值:

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

  selectedNavItem(item: number) {
    this.someService.isFixed(true);
  }
}

回答by Kody

See Angular2 Component Interaction(has code examples).

请参阅Angular2 组件交互(有代码示例)。

The short answer to your question is that it really just depends on what you are trying to do. Even then, there are multiple ways to do what you want to do even if it's not really intended for it. So, I think it's best if you just take a few minutes to look at their documentation about Component Interaction and Forms.

对您的问题的简短回答是,这实际上仅取决于您要尝试做什么。即使那样,也有多种方法可以做你想做的事情,即使它不是真正的目的。因此,我认为您最好花几分钟时间查看他们关于组件交互和表单的文档。

My personal preference is to use events when a property has changed. The ngOnChangesevent can be used for this but I prefer to work with @Inputand @Output, and form value changed events(Angular2 Forms).

我个人的偏好是在属性发生变化时使用事件。该ngOnChanges事件可用于此,但我更喜欢使用@Inputand@Output表单值更改事件Angular2 Forms)。

Hope this helps and gives you a direction you want to take.

希望这会有所帮助,并为您提供想要采取的方向。