将数组从父级传递给子级

时间:2018-04-12 13:51:15

标签: angular typescript parent-child

我正在尝试将数组从父级传递给子级,但是当我在子级中查看时,我得到值DvnlandingComponent.ts。我在这里试过解决方法。

import { HttpService } from '../services/http.service'; export class DvnlandingComponent implements OnInit { count: number = 0; constructor(private http: Http, private service: HttpService) ngOnInit() { this.printConfigNames(); } printConfigNames() { this.service.getAllconfigNames(); } } (父母)

<results-component *ngIf="activeTab === 'Results'" [cfn]="configNames"></results-component>

HTML

ResultsComponent.ts

import { DvnlandingComponent } from './../dvn-landing.component'; export class ResultsComponent implements OnChanges { @Input() cfn: any[] = []; ngOnit() { console.log(this.cfn); } ngOnChanges(changes: SimpleChanges) { if (typeof changes['cfn'] !== 'undefined') { console.log(this.cfn); } } printConfigNames() { console.log(this.cfn); } (孩子)

        <select>
                <option selected>Select Config Name</option>
            <option *ngFor="let n of cfn" value="n" (click)="printConfigNames()">{{n}}</option>
        </select>

HTML

@Injectable()
export class HttpService {
  getdata: any;
  count: number = 0;
  public configNames = [];
  constructor(private http: Http) { }

      getAllconfigNames() {
        let headers = new Headers();
        headers.set('Content-Type', 'application/json');
        headers.set('JsonStub-User-Key', '157abb1d-fc96-4e00-83c7-9f286f6ef518');
        headers.set('JsonStub-Project-Key', '720d2af8-f159-41b4-9746-0476793869b4');

        let getUrl = 'http://jsonstub.com/getAllSchedulerConfigs';
        return this.http.get(getUrl, {headers: headers})
        .subscribe(res => {
            this.getdata  = res.json();
            while (this.count < this.getdata.length) {
            this.configNames.push(this.getdata[this.count]['configName']);
            this.count++;
        }
        });
      }
      getData() {
        return this.configNames;
      }

    }

我的服务

$qb = $this->createQueryBuilder('tdd');
$qb->select('tdd')
->where($qb->expr()->eq('tdd.disable_date', ':dat'))
->setParameter('dat', new \DateTime());
return $qb->getQuery()->getOneOrNullResult();

2 个答案:

答案 0 :(得分:1)

您的代码存在许多问题。

(i)您的父组件中没有 configNames 。确保你已定义它。

configNames: any[];

printConfigNames() {
    this.service.getAllconfigNames().subscribe(res => this.configNames = res);
}

(ii)您正在初始化为子组件上的空数组,这将清除其中的元素

 @Input() cfn: any[] = [];

将其更改为

 @Input() cfn: any[] ;

(iii)您的子组件应实施 OnInit

导出类ResultsComponent实现OnInit {

 ngOnInit(): void {
     console.log(this.cfn);
 }

答案 1 :(得分:1)

没有看到服务,但假设您正在使用observables,在父级中:

configNames: any[];

printConfigNames() {
    this.service.getAllconfigNames().subscribe(res => this.configNames = res);
}

应该有希望帮助。