簡體   English   中英

如何從Angular2的父級中的dataService接收的數據傳遞給子級

[英]How to pass data received from dataService in parent to child in Angular2

我有一個父組件app-parentapp-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語句,在嘗試對其進行任何操作之前先檢查其是否有價值,因為在第一次執行ngOnChangestitle將是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM