Javascript 使用观测值传播角度2的变化
我有两个部分,一个是父母,一个是孩子:Javascript 使用观测值传播角度2的变化,javascript,angular,rxjs,Javascript,Angular,Rxjs,我有两个部分,一个是父母,一个是孩子: // Parent Directive @Component({ selector: 'parent-directive', template: ` <button (click)="nextVal($event)"></button> <button (click)="prevVal($event)"></button> <child-directive [cont
// Parent Directive
@Component({
selector: 'parent-directive',
template: `
<button (click)="nextVal($event)"></button>
<button (click)="prevVal($event)"></button>
<child-directive [content]="myValue"></child-directive>`,
directives: [ChildDirective]
})
export class ParentDirective {
public myValue : string;
constructor() {this.myValue = "Hello";}
nextVal() {this.myValue = "Next";}
prevVal() {this.myValue = "Prev";}
}
//父指令
@组成部分({
选择器:“父指令”,
模板:`
`,
指令:[儿童指令]
})
导出类ParentDirective{
公共myValue:string;
构造函数(){this.myValue=“Hello”;}
nextVal(){this.myValue=“Next”}
prevVal(){this.myValue=“Prev”}
}
这是child指令:
// Child directive
type ObservableContent = Observable<string>;
@Component({
selector: 'child-directive',
template: `<div></div>`
})
export class ChildDirective {
@Input() content : ObservableContent;
subscription : Subscription;
constructor() {
// I instantiate the content property as an observer. I want to see if it logs anything.
this.content = new Observable<string>(ob => {console.log('constructor', ob)});
// I'm trying to get the propagated values here.
this.subscription = this.content.subscribe(value => { console.log('value', value);});
}
}
//子指令
类型可观测内容=可观测;
@组成部分({
选择器:“子指令”,
模板:``
})
导出类指令{
@Input()内容:ObservableContent;
认购:认购;
构造函数(){
//我将content属性实例化为一个观察者。我想看看它是否记录了任何内容。
this.content=newobservable(ob=>{console.log('constructor',ob)});
//我试图在这里获得传播的值。
this.subscription=this.content.subscripte(值=>{console.log('value',value);});
}
}
让我详细说明我在这里要做的事情。我有一个子组件嵌套在父组件中。父对象有两个按钮,next
和prev
,单击它们可以更改绑定到父对象范围的属性
子对象有另一个属性,
content
,它绑定到父对象的myValue
范围属性。当我在父对象中更新myValue
时,我希望更改子对象的内容
属性。但是,当我尝试订阅该值时,从未调用订阅侦听器。我做错了什么?正如我所看到的内容
是一个字符串,而不是可观察的。因此,您不需要在此处使用.subscribe
,因为它会抛出错误
在子组件中,此.content
将始终为您提供最新的值。只需使用changeDetection:ChangeDetectionStrategy.OnPush。这确保仅当组件的一个输入属性发生更改时,angular才会更新组件
要获取组件中内容的最新值
,请使用angular提供的ngOnChanges
生命周期方法
//子指令
类型可观测内容=可观测;
@组成部分({
选择器:“子指令”,
模板:`{content}}`,
changeDetection:ChangeDetectionStrategy.OnPush
})
导出类指令{
@Input()内容:ObservableContent;
ngOnChanges(更改){
log('newcontent'+changes.content.currentValue);
console.log('old content'+changes.content.previousValue);
}
}
由于Angular的更改检测,模板中的内容将始终反映更新后的值。我认为我们正在寻找捕捉
内容的值更改时刻的方法,而不仅仅是将其输出到模板中。对于在模板中输出,您不需要任何可观察的东西。我不需要将内容值写入模板。我需要将其捕获为子组件的属性。加载组件时,日志只显示一次,但更改父值时不会显示。请记住,我试图将更改从父对象传播到子对象。“当我更新父对象中的myValue时,我希望子对象的内容属性发生更改。但是,当我尝试订阅该值时,从未调用订阅侦听器。我做错了什么。这是你的问题,我的答案是肯定的。也许你想修改你的问题,以便我能更好地理解你的要求。请提供一把小提琴。当我使用你的答案时,它不起作用。