【问题标题】:Not able pass data one component to another component using SharedService in angular?无法使用 SharedService 以角度将数据一个组件传递给另一个组件?
【发布时间】: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());
    }



}

here is my code

【问题讨论】:

    标签: angular


    【解决方案1】:

    问题在于您的每个组件中的providers: [ SharedService ]通过在每个组件中将服务声明为提供者,您将为每个组件创建一个唯一的单例服务。

    您需要向一个父组件或包含这两个组件的模块提供服务。

    此 StackBlitz 演示了将服务声明为模块中的提供者,其中包含两个组件 StackBlitz Demo

    此堆栈演示了在父组件中将服务声明为提供者 StackBlitz Demo

    【讨论】:

    • 我为你添加了两个 StackBlitz 演示。看看答案
    • 在我的情况下,ts 文件中的两个组件(同一页面)我可以为此做什么。这里您使用的是两个不同的 ts 文件
    • 从您的代码看来,DialogOverviewExample 是您的父组件,因此您可以将 SharedService 作为该组件的提供者。
    • stackblitz.com/edit/angular-mrvej3-m6wtru?file=app/… .getting error No provider for SharedService .help me on this
    • 这里我刚刚看到你的问题中有一个 StackBlitz:查看这个新的 Stack of your question stackblitz.com/edit/angular-mrvej3-cusfjw
    猜你喜欢
    • 2019-08-03
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2021-10-17
    • 2017-05-19
    相关资源
    最近更新 更多