从服务 Angular 设置和获取数据

时间:2021-06-25 08:50:10

标签: angular typescript

我想通过在每个子组件的 ts 文件中直接注入提供程序来使父组件与子组件通信,因为我想使用 get & set 获取数据,但我不明白该怎么做?

服务

export class ProductSharingDataService {

  public productName!:any;

  constructor() { }

  setRowName(selectedTableRowData:any){
    this.productName = selectedTableRowData;
  }

  getRowName():string{
    return this.productName;
  }

}

components.ts

    @Component({
          selector: 'app-product-page',
          templateUrl: './product-page.component.html',
          styleUrls: ['./product-page.component.css'],
          providers: [ProductSharingDataService] // injected service here
        })
        export class ProductPageComponent {
        
          public selectedArrayParent!: Product;
        
          constructor(private productSharingDataService: 
                      ProductSharingDataService) {
            this.productSharingDataService.getRowName();  
            }
        
          receive($event: any) {
            this.selectedArrayParent = $event 
// I need to retrieve this data ( $event ) 
          }
        
        }

2 个答案:

答案 0 :(得分:2)

您至少有 2 种方式与组件父组件 <-> 子组件通信:

注意:您必须始终放置适当的类型,而不是“any”

1) 将服务用作“商店”:

服务 https://angular.io/guide/component-interaction#parent-and-children-communicate-using-a-service

export class ProductSharingDataService {

  private _productName!:any;

  set rowName(selectedTableRowData:any){
    this._productName = selectedTableRowData;
  }

  get rowName():string{
    return this._productName;
  }

  constructor() { }

}

  constructor(private productSharingDataService: ProductSharingDataService) {
     this.productSharingDataService.rowName = 'Info (object, string, whatever...) you want to pass to child';  
  }

孩子

name: any;

  constructor(private productSharingDataService: ProductSharingDataService) {
     this.name = this.productSharingDataService.rowName;
  }

2) 使用@input() 和@output: https://angular.io/guide/component-interaction

- 在子组件中:

import { ..., EventEmitter, ..., Output } from '@angular/core';
...


 @Component({
      selector: 'app-child', ....



   @Input() varNameIn: any[] = []; 
    @Output() varNameOut: EventEmitter<any> 
      = new EventEmitter();
    ...

当你想将某些东西传递给父级时:

const infoToParent:any = 'Info (object, string, whatever...) you want to pass to parent';
this.varNameOut.emit(info);

- 在组件父级中:

HTML:

...
<app-child [varNameIn]="infoToChild" (varNameOut)="parentMethodToUseVarNameOutContent($event)"></app-child>
....

TS:

    ...

    // Instead of 'any', you have to put the same type of varNameOut in the child:
    ...
    const infoToChild="Info (object, string, whatever...) you want to pass to child";
    ...
    parentMethodToUseVarNameOutContent(varNameOut: any){
       console.log(varNameOut);
    }
    ...

答案 1 :(得分:0)

使用 @input() and @output 装饰器,您还可以实现从一个组件到另一个组件的数据。但是,以下方法使用 @output 装饰器并希望它可以解决您的问题。

在接收器组件(比方说 ProductPageParentComponent)打字稿中,您必须创建一个方法来接收 productName 变量的值,如下所示:

export class ProductPageParentComponent{

constructor() { }

productName: string;

receiveStringValue($event) {
  this.productName= $event;
 }
}

在接收器组件 html 中输入以下内容:

<app-product-child-page (stringValueEvent)="receiveStringValue($event)"></app-product-child-page>
<h1>{{productName}}<h1>

在发件人组件(假设为 ProductPageChildComponent)打字稿(app-product-child-page 选择器)中,您应该使用 stringValueEvent 装饰器声明一个 @Output() 变量并将其设置为等于新的事件发射器。

export class ProductPageChildComponent{

  productName: string;

  @Output() stringValueEvent = new EventEmitter<string>();

  constructor() { }

  ngOnInit(): void {
    this.productName= "Sample Product";
    this.stringValueEvent.emit(this.productName);
  }
}
相关问题