在我的Angular 4项目中,我正在通过服务调用传递一个值表单父组件。子组件正在接收该值,也可以在我的HTML中使用。但是当我在我的子组件打字稿文件中安慰传递的值时,它显示未定义。
以下是我的代码段一步一步: -
restaurantlayout.component.ts(父组件ts文件):
import { Component, OnInit, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RestaurantService } from '../../services/restaurant.service';
import { Response } from '@angular/http';
@Component({
selector: 'app-restaurantlayout',
templateUrl: './restaurantlayout.component.html',
styleUrls: ['./restaurantlayout.component.css'],
providers: [RestaurantService]
})
export class RestaurantlayoutComponent implements OnInit {
public menuarray;
public bannerarray;
public popularArray; //passing data
constructor(private restaurantservice:RestaurantService) { }
ngOnInit() {
this.restaurantservice.getPartcularRestaurantDetailsByidOrSlug()
.subscribe((data:Response)=>{
this.menuarray = data.json().menu['menu'] ;
this.bannerarray = data.json().basicDetails['basicDetails'];
this.popularArray = data.json().popular['popular'];
}
);
}
}
restaurantlayout.component.html(Parent Alyout Html文件)
<section class="restaurant-details-main">
<app-restaurantbanner [bannerSection]="bannerarray"></app-restaurantbanner>
</section>
<section class="restaurant-mid-body">
<div class="wraper">
<div class="row">
<app-restaurantmenu [menuSection]="menuarray"></app-restaurantmenu>
<app-restaurantrecomend [popularSection]="popularArray">
</app-restaurantrecomend> <!-- passed here -->
<app-restaurantbasket>
</app-restaurantbasket>
</div>
</div>
</section>
子组件打字稿文件代码: -
import { Component, OnInit, Input } from '@angular/core';
import { NgModule } from '@angular/core';
@Component({
selector: 'app-restaurantrecomend',
templateUrl: './restaurantrecomend.component.html',
styleUrls: ['./restaurantrecomend.component.css']
})
export class RestaurantrecomendComponent implements OnInit {
@Input() popularSection:string[];
public decrementDisabled = true;
constructor() { }
ngOnInit() {
console.log(this.popularSection); //giving undefined but available
//in HTML file
}
increment(popular){
this.decrementDisabled = false;
popular.count++;
}
decrement(popular){
popular.count--;
}
addTobasket(popularitem){
popularitem.cost = (popularitem.count*popularitem.item_price);
this.data.changeBasketState(popularitem);
}
}
答案 0 :(得分:3)
您的父组件使用异步操作检索df2[~df2[df1.columns].astype(str).sum(1).isin(df1.astype(str).sum(1))]
,然后将其作为popularArray
传递给子项。这意味着当子组件运行其popularSection
方法时,服务调用尚未完成,ngOnInit
仍未定义。
将您的popularSection
更改为ngOnInit
,您将看到变量首先未定义,并且只要服务返回该变量,子项就会记录正确的值。
答案 1 :(得分:0)
输入属性的值是在异步操作中从父级设置的。
您可以使用子组件中的setter来获取ts文件中的值。 只要在输入属性中检测到更改,就会执行输入设置器。