我正在处理一个问题。我叫一个API。来自api的响应后。我想将值传递给子组件。在那里,我将执行方法并获得响应。在屏幕上显示。请帮助我。
代码:
ngOnInit() {
const userId = '2';
this.apiService.collectIds(userId)
.subscribe(ids => {
this.ids = ids
}, error => {
console.log('error', error);
});
}
子组件:
<app-chart [ids]="ids"></app-chart>
答案 0 :(得分:1)
在父子组件之间进行通信的最常见方式是使用@Input和@Output装饰器。
对于您的特定情况,您必须使用@Input装饰器
在子组件应用图表中,您将这样声明:
@Input() ids: number; // Or which ever the type you have
在您的示例中,您从服务中获取价值。当父组件中的@Input元素发生更改时,Angular将自动进行更新。如果您不必在输入的更改上执行任何方法(在子组件中),则无需执行其他任何操作(例如订阅,异步管道等)。
答案 1 :(得分:-1)
您是否尝试在视图中放置异步?
<app-chart [ids]="ids | async"></app-chart>
有关异步使用情况的更多信息https://angular.io/api/common/AsyncPipe
答案 2 :(得分:-1)
尝试
ngOnInit() {
const userId = '2';
this.collectIds$ = this.apiService.collectIds(userId);
}
在html中:
<app-chart [ids]="(collectIds$|async)?.ids"></app-chart>