【发布时间】:2018-10-15 01:55:46
【问题描述】:
在我的 Angular 4 项目中,我传递了一个来自服务调用的父组件的值。子组件正在接收该值,并且在我的 HTML 中也可用。但是当我在子组件打字稿文件中安慰传递的值时,它显示为未定义。
这是我的代码 sn-ps 一步一步:-
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(父 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);
}
}
【问题讨论】:
-
这可能与this question 重复。看起来是填充
@Input字段的异步服务导致了这种情况。 -
输入属性的值是在异步操作中从父级设置的...
标签: angular