在AngularJS中,你可以使用$scope的$watch函数指定观察者来观察作用域变量的变化。在Angular中,什么与监视变量变化(比如组件变量)是等价的?
当前回答
这并没有直接回答这个问题,但我在不同的情况下遇到过这个Stack Overflow问题,以解决我在angularJs中使用$watch的问题。我最终使用了另一种方法,而不是目前的答案中所描述的方法,并且想要分享它,以防有人发现它有用。
我用来实现类似$watch的技术是在Angular服务中使用一个BehaviorSubject(这里有更多关于这个主题的内容),并让我的组件订阅它,以便获得(监视)更改。这类似于angularJs中的$watch,但需要更多的设置和理解。
在我的组件中:
export class HelloComponent {
name: string;
// inject our service, which holds the object we want to watch.
constructor(private helloService: HelloService){
// Here I am "watching" for changes by subscribing
this.helloService.getGreeting().subscribe( greeting => {
this.name = greeting.value;
});
}
}
为我服务
export class HelloService {
private helloSubject = new BehaviorSubject<{value: string}>({value: 'hello'});
constructor(){}
// similar to using $watch, in order to get updates of our object
getGreeting(): Observable<{value:string}> {
return this.helloSubject;
}
// Each time this method is called, each subscriber will receive the updated greeting.
setGreeting(greeting: string) {
this.helloSubject.next({value: greeting});
}
}
这是一个关于Stackblitz的演示
其他回答
这个行为现在是组件生命周期的一部分。
组件可以在OnChanges接口中实现ngOnChanges方法来访问输入更改。
例子:
import {Component, Input, OnChanges} from 'angular2/core';
@Component({
selector: 'hero-comp',
templateUrl: 'app/components/hero-comp/hero-comp.html',
styleUrls: ['app/components/hero-comp/hero-comp.css'],
providers: [],
directives: [],
pipes: [],
inputs:['hero', 'real']
})
export class HeroComp implements OnChanges{
@Input() hero:Hero;
@Input() real:string;
constructor() {
}
ngOnChanges(changes) {
console.log(changes);
}
}
这并没有直接回答这个问题,但我在不同的情况下遇到过这个Stack Overflow问题,以解决我在angularJs中使用$watch的问题。我最终使用了另一种方法,而不是目前的答案中所描述的方法,并且想要分享它,以防有人发现它有用。
我用来实现类似$watch的技术是在Angular服务中使用一个BehaviorSubject(这里有更多关于这个主题的内容),并让我的组件订阅它,以便获得(监视)更改。这类似于angularJs中的$watch,但需要更多的设置和理解。
在我的组件中:
export class HelloComponent {
name: string;
// inject our service, which holds the object we want to watch.
constructor(private helloService: HelloService){
// Here I am "watching" for changes by subscribing
this.helloService.getGreeting().subscribe( greeting => {
this.name = greeting.value;
});
}
}
为我服务
export class HelloService {
private helloSubject = new BehaviorSubject<{value: string}>({value: 'hello'});
constructor(){}
// similar to using $watch, in order to get updates of our object
getGreeting(): Observable<{value:string}> {
return this.helloSubject;
}
// Each time this method is called, each subscriber will receive the updated greeting.
setGreeting(greeting: string) {
this.helloSubject.next({value: greeting});
}
}
这是一个关于Stackblitz的演示
你可以使用getter函数或get访问器来充当angular 2上的watch。
请看这里的演示。
import {Component} from 'angular2/core';
@Component({
// Declare the tag name in index.html to where the component attaches
selector: 'hello-world',
// Location of the template for this component
template: `
<button (click)="OnPushArray1()">Push 1</button>
<div>
I'm array 1 {{ array1 | json }}
</div>
<button (click)="OnPushArray2()">Push 2</button>
<div>
I'm array 2 {{ array2 | json }}
</div>
I'm concatenated {{ concatenatedArray | json }}
<div>
I'm length of two arrays {{ arrayLength | json }}
</div>`
})
export class HelloWorld {
array1: any[] = [];
array2: any[] = [];
get concatenatedArray(): any[] {
return this.array1.concat(this.array2);
}
get arrayLength(): number {
return this.concatenatedArray.length;
}
OnPushArray1() {
this.array1.push(this.array1.length);
}
OnPushArray2() {
this.array2.push(this.array2.length);
}
}
下面是为模型使用getter和setter函数的另一种方法。
@Component({
selector: 'input-language',
template: `
…
<input
type="text"
placeholder="Language"
[(ngModel)]="query"
/>
`,
})
export class InputLanguageComponent {
set query(value) {
this._query = value;
console.log('query set to :', value)
}
get query() {
return this._query;
}
}
如果你想让它双向绑定,你可以使用[(yourVar)],但你必须实现yourVarChange事件,并在每次变量改变时调用它。
像这样的东西来跟踪英雄的变化
@Output() heroChange = new EventEmitter();
然后当你的英雄发生变化时,调用this.heroChange.emit(this.hero);
[(英雄)]绑定将为您完成其余的工作
请看例子:
http://plnkr.co/edit/efOGIJ0POh1XQeRZctSx?p=preview
推荐文章
- NullInjectorError: AngularFirestore没有提供程序
- 如何在Angular2中截断文本?
- 如何在Angular2 ngSwitch语句中使用typescript enum值
- AngularJS控制器的生命周期是什么?
- Angular CLI错误:serve命令需要在Angular项目中运行,但是找不到项目定义
- 找到合成属性@panelState。请在您的应用程序中包含“BrowserAnimationsModule”或“NoopAnimationsModule”。
- 在Angular中上传文件?
- 模板驱动表单和响应式表单之间的实际区别是什么?
- Angular 2+和debounce
- $destroy是否删除事件监听器?
- 用布尔值将单选按钮绑定到模型
- AngularJS只适用于单页应用程序吗?
- 如何以及在哪里使用::ng-deep?
- 禁用在角材质对话框区域外单击以关闭对话框(angular 4.0+版本)
- Angular 2模板中的标签是什么意思?