[英]How to pass data received from dataService in parent to child in Angular2
我有一个父组件app-parent和app-child 。 在app-parent中,我成为DataService中的数据
@Component({
selector: 'app-parent',
providers: [DataService]
})
export class Part1Component implements OnInit {
public title: string;
constructor(public dataService: DataService) {}
ngOnInit() {
this.dataService.get().subscribe(data => {
this.itemsSource = this.dataService.convert(data, 1);
this.title = this.itemsSource[0];
});
return this.title;
}
模板
<div id="content">Hallo!</div>
<app-child [title]='title'></app-child>
我想将标题传递给子组件。 所以在我的孩子部分是:
@Injectable()
export class InfoComponent implements OnInit, OnDestroy {
@Input() title: any;
ngOnInit() {
console.log('Show me title')
console.log(this.title);
}
因此,我尝试使用@Input()传递我的数据,但是它不起作用(如果标题,我将变为未定义)。 我想这是因为首先在我的父组件中,我从DataService变成了数据(因为如果我将app-parent中的 title设置为开头的值,例如
public title = 'Hola!';
有用.. )
你能告诉我如何解决这个问题吗?
您的数据是异步获取的,因此在子组件OnInit
被触发时, title
尚未有值。 使用OnChanges
我们可以监视@Input
更改,因此您可以执行以下操作:
ngOnChanges() {
console.log('Show me title')
console.log(this.title);
}
只要输入title
发生变化,就会触发。 如果您需要对title
进行某些操作,则最好设置一个if
语句,在尝试对其进行任何操作之前先检查其是否有价值,因为在第一次执行ngOnChanges
, title
将是undefined
。
附带说明一下,我不知道您要如何使用父级中的return title
进行操作,但这不会返回任何从内部subscribe
获得的值。 另外,为什么您的子组件被标记为Injectable
? 这与您的问题无关,但要指出这一点。
当您导航到子视图时
import { NavController,........} from 'ionic-angular';
.
.
this.dataService.get().subscribe(data => {
this.itemsSource = this.dataService.convert(data, 1);
this.title = this.itemsSource[0];
this.navCtrl.push(ChildPage, { title: this.title })
});
.
.
当您进入子视图时
import { NavParams,............} from 'ionic-angular';
.
.
this.title = navParams.get('title')
.
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.