[英]Angular; Sharing data between this components
I'm new to Angular and I have this problem here: I want to pass the data that I have from this service+component to another component. 我是Angular的新手,我在这里遇到这个问题:我想将我从该service +组件获得的数据传递给另一个组件。
I have a service doing this: 我有这样做的服务:
getRecs() {
let recsSub = new Subject<any>();
let recsSubObservable = from(recsSub);
this.socket.on('recs', (recsStatus: any) => {
recsSub.next(recsStatus);
});
return recsSubObservable;
}
Then I have this parent component 然后我有这个父组件
private misRecs = null;
snackBarShown = false;
constructor (private appSocketIoService: AppSocketIoService, private snackbar: MatSnackBar) {
let recsObservable = this.appSocketIoService.getRecommendations();
recsObservable.subscribe((recsStatus: any) => {
console.log(recsStatus);
this.misRecs = {};
for(let property in recsStatus.output){
if (recsStatus.output[property]) {
this.misRecs[property] = recsStatus.output[property];
}
};
this.snackbar.openFromComponent (CustomSnackBar, { duration: 5000, });
});
}
What I need is to populate a list in another component with the values obtained from recsStatus
but I don't know how to do it. 我需要的是用从
recsStatus
获得的值填充另一个组件中的列表,但是我不知道该怎么做。
Thank you all for your help. 谢谢大家的帮助。
If the component is a child component of your component (parent) you describe in the listing you can use the @Input()
annotation. 如果该组件是您的组件(父)的子组件,则可以使用
@Input()
注释。
@Component({
selector: 'child-comp',
template: `
<div>
{{ localRecStatus | json }}
</div>
`
})
export class ChildComponent {
@Input()
localRecStatus: [];
}
Now you can use the component in HTML file of your parent component like this: 现在,您可以像下面这样使用父组件的HTML文件中的组件:
<child-comp [localRecStatus]="recStatus"></child-comp>
With this, you can use recStatus in your child component. 这样,您可以在子组件中使用recStatus。 However,
recStatus
must be a public variable of the parent component. 但是,
recStatus
必须是父组件的公共变量。 With this technique, you can pass any data to child components. 使用这种技术,您可以将任何数据传递给子组件。 There is also an
@Output()
annotation you can use in combination with an EventEmitter to send data to the parent component. 还有一个
@Output()
批注,可以与EventEmitter结合使用,以将数据发送到父组件。 If the component is not a child, probably a better way is to communicate via a Service between both components. 如果组件不是子组件,则可能更好的方法是通过服务在两个组件之间进行通信。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.