簡體   English   中英

如何使用依賴注入從angular2中的父組件訪問值?

[英]How can i access the values from parent component in angular2 using dependency injection?

我有兩個組件,一個父母和一個孩子,我想從孩子使用DI訪問父組件中的變量,但我沒有得到那個。我做了一個plunker演示http://plnkr.co/edit/fcfweLJAmadKVWKXF25l?p=preview ...我試圖從child訪問變量的值並且正確地得到但不是從父到子。這就是我在子組件中訪問變量的方式

@Component({
  selector: 'child',
  providers:[AppComponent]
  template: '<h1>My second Angular 2 App</h1>'
})
class NameComponent {
  name:string;
  constructor(AppComponent: AppComponent) {
    this.name = AppComponent.getName();
    console.log(this.name);
  }
}

我想知道是否可以使用DI從父級訪問變量? 請告訴我如何獲取價值觀

是的,這是可能的,但你需要利用forwardRef如下所述,因為你不能使用吊裝:

@Inject(forwardRef(() => AppComponent)) app:AppComponent

這是完整的樣本:

@Component({
  selector: 'child',
  providers:[AppComponent]
  template: '<h1>My second Angular 2 App</h1>'
})
class NameComponent {
  name:string;
  constructor(@Inject(forwardRef(() => AppComponent)) appComponent: AppComponent) {
    this.name = appComponent.getName();
    console.log(this.name);
  }
}

@Component({
})
class AppComponent {
}

這是更新的plunkr: http ://plnkr.co/edit/brmQ01wFWrWvXmxpJpCc?p = preview。

這篇由Christoph Burgdorf撰寫的文章也可以幫助你:

如果將類定義到單獨的模塊/文件中,我們還應該注意循環依賴:父組件導入子組件1,子組件導入父組件...

您必須在父組件中注入服務(在提供程序條目中),設置要使用的值,而不是在子組件中使用它。

@Component({
  selector: 'app',
  providers:[YourService]
  template: '<childCmp></childCmp>'
})
class AppComponent {
  constructor(private yourService: YourService) {
    this.yourService.setData(data);
  }
}

@Component({
  selector: 'childCmp',
  template: '{{yourService.getData()}}'
})
class ChildCmp {
  constructor(private yourService: YourService) {
    this.yourService.setData(value);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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