Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 将数据传递给子组件(从web服务接收的数据不附加到子组件上)_Angular_Typescript - Fatal编程技术网

Angular 将数据传递给子组件(从web服务接收的数据不附加到子组件上)

Angular 将数据传递给子组件(从web服务接收的数据不附加到子组件上),angular,typescript,Angular,Typescript,我试图在服务加载后分配数据,以便更好地理解代码 服务 getcampaigndata(slug: any): Promise<any> { return this.http .get('service url'+slug) .toPromise() .then((res) => res.json()) .cat

我试图在服务加载后分配数据,以便更好地理解代码

服务

getcampaigndata(slug: any): Promise<any> {                
     return this.http
                .get('service url'+slug)
                .toPromise()
                .then((res) => res.json())
                .catch(this.handleError);
}
子组件

public slug: string;
public data: any = {};

this.campaign.getcampaigndata(this.slug).subscribe(params => {
      this.data = params;
});
import {CampaignComponent} from '../../campaign.component';

constructor(private shared: SharedService,private route:ActivatedRoute,public campaign: CampaignComponent) { };

 ngOnInit() {
     console.log(this.campaign.slug);
     console.log(this.campaign.data);
 }
正如您所看到的,我已经在另一个组件上导入了
activitycomponet
,它对于slug非常有效,因为
slug
是在运行时分配的,但是对于
数据
它由于http请求而未分配。有人能解决这个问题吗


使用this.data=JSON.parse(localStorage.getItem('currentCampaig‌​n')Web服务实例运行良好

使用
@Input
装饰器将数据传递给子组件

<child-component [myData]="data"></child-component>

而且当调用
ngOnInit()
时,传递的数据尚未绑定。因此,您需要另一个生命周期事件,
ngochanges()
ngAfterViewInit()

您也可以参考下面的链接,该链接解释了不同的方法:


如何将数据从父组件传递到子组件?因为您从服务获取数据,所以最好在数据可用后加载子组件。例如,
@AvinashRaj通过导入父组件。我试过
,但它对immidate赋值有效。我喜欢本地存储。未通过此方法分配web服务数据您必须使用
@Input
将数据从父组件传递到子组件,我认为导入将不起作用。好的,让我们尝试一下
<child-component [myData]="data"></child-component>
export class ChildComponent {
  @Input() myData;
}