【发布时间】:2018-04-12 15:10:02
【问题描述】:
无法使用 SharedService 将数据从一个组件传递到另一个组件
我创建了共享服务,
@Injectable()
export class SharedService{
myData;
constructor(){
this.myData= {};
}
setMyData(val: object){
this.myData= val;
}
getMyData(){
return this.myData;
}
}
我想将数据“DialogOverviewExample”组件传递给“DialogOverviewExampleDialog”组件。
this.result = [{ "name":"John", "age":30, "car":null }];
我尝试使用 sharedService 传递上述数据,但我没有在 DialogOverviewExampleDialog 组件中获取数据
@Component({
selector: 'dialog-overview-example',
templateUrl: 'dialog-overview-example.html',
styleUrls: ['dialog-overview-example.css'],
providers: [ SharedService ]
})
export class DialogOverviewExample {
constructor(public dialog: MatDialog, private sharedService: SharedService) {}
ngOnInit() {
this.result = [{ "name":"John", "age":30, "car":null }];
this.sharedService.setMyData(this.result);
}
}
DialogOverviewExampleDialog 组件
@Component({
selector: 'dialog-overview-example-dialog',
templateUrl: 'dialog-overview-example-dialog.html',
providers: [ SharedService ]
})
export class DialogOverviewExampleDialog {
constructor(
public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
@Inject(MAT_DIALOG_DATA) public data: any,
sharedService: SharedService)
{
console.log(sharedService.getMyData());
}
}
【问题讨论】:
标签: angular