【问题标题】:Angular 4 - create new Child Component in Parent with DIAngular 4 - 使用 DI 在父级中创建新的子组件
【发布时间】:2017-12-09 04:14:58
【问题描述】:

我有一个用 *ngFor 显示的子组件数组。 我的子组件现在需要注入 DataService。当编译器现在抱怨构造函数需要 DataService 的实例时,我该如何创建一个新的 ChildComponent()?

父组件:

import { Component, OnInit } from '@angular/core';
import {SkipComponent} from "../skip/skip.component";
import { DataService } from '../services/data.service';


@Component({
  selector: 'app-skips',
  templateUrl: './skips.component.html',
  styleUrls: ['./skips.component.css'],
  providers: [ DataService ]
})
export class SkipsComponent implements OnInit {

  public childItems: SkipComponent[] = [new SkipComponent()];

  public removeSkip(skip){

    var index = this.childItems.findIndex((elt) => (elt===skip));
    if (index != -1) {
      this.childItems.splice(index, 1);
    }
  }

  public onAdd(){
    this.childItems.push(new SkipComponent());
  }

  constructor() {
  }

  ngOnInit() {
  }

子组件:

import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { DataService } from '../services/data.service';

@Component({
  selector: 'app-skip',
  templateUrl: './skip.component.html',
  styleUrls: ['./skip.component.css'],
  providers: [ DataService ]
})
export class SkipComponent implements OnInit {

  @Input() skip: any;

  @Output()
  onSkipRemove: EventEmitter<any> =  new EventEmitter();

  containers: any[];

  public removeSkip(){
    this.onSkipRemove.emit(
      this.skip
     )
  }

  constructor(private dataService: DataService) {
    this.dataService.getContainers().subscribe(res=>this.containers=res);
  }

  ngOnInit() {
  }

}

【问题讨论】:

    标签: angular dependency-injection angular2-services


    【解决方案1】:

    DI 发生在框架实例化时,当您使用new 运算符显式实例化SkipComponent 时,您需要传入服务。所以你的解决方案是:

    在顶层 (SkipsComponent) 获取DataService

    constructor(private dataServices: DataService){}
    

    然后当您创建 SkipComponent 时将其传递给构造函数:

    this.childItems.push(new SkipComponent(this.dataService));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 2018-01-04
      • 2019-07-22
      • 1970-01-01
      相关资源
      最近更新 更多