【问题标题】:How can i pass multiple variables from one component to the service in angular 9?如何将多个变量从一个组件传递给 Angular 9 中的服务?
【发布时间】:2020-09-16 18:20:43
【问题描述】:

如何将多个变量从一个组件传递到服务并在 angular 9 中将其获取到另一个组件中? 我非常努力地解决了这个问题,但我找不到任何解决方案。 我正在尝试将包含一些数据的变量从 sendComponent 传递/发送到服务,并将相同的数据获取到另一个 receiveComponent。单击 send.Html 上的按钮并导航到 receiveComponent。

sent.Html: 我想在这个 html 中按下 OK 按钮后推送数据

<button class="btn btn-primary pull-right" (click)="onPushData()">
   <i class="fa fa-check" aria-hidden="true"></i> 
    OK
</button>

sendComponent: secondTableData、totalPrice 和 totalPrice 这些是包含需要传递给 service.ts 的数据的变量 可能这是错误的方法强>

onPushData(){                          
    let tData = this.secondTableData  // want to push secondTableData variable
    let t = this.totalPrice;          // want to push totalPrice variable
    let d = this.totalPrice           // want to push totalQuantity variable
    this.dataShareService.onPushTable(tData);
    console.log(tData);
    this.routerService.navigate(['./billprint'])
  }

Service.ts:

@Injectable({
  providedIn: 'root'
}) 

export class DataShareService { 

  onPushTable(tData) {
  --Do something here--
  }
 }

receiveComponent: 我想在这个组件中获取数据

recDataFromService() {
  --do something here--
}

receive.Html: 在此处显示数据

<tr *ngFor="let data of recData;let i = index">
   <td>{{i+1}}</td>
   <td>{{data.itemName}}</td>
   <td>{{data.Quantity}}</td>
   <td>{{data.retailRate}}</td>
</tr>

请帮我解决这个问题...如果您对此有任何想法,请分享您的答案..

示例: 这是在 secondTableData 中包含数据数组(itemName, Quantity,retailRate ....)的代码

  //To Copy data of First table to Second table
   secondTableData = [];
   updateSecondTable(data) {
   let foundItem = this.secondTableData.find((item) => item.itemName === 
     data.itemName);
   if (foundItem) {
    foundItem.rate = data.retailRate;
   foundItem.Quantity += 1;
   foundItem.retailRate += data.retailRate;
   this.getColumnTotal();   //  <----- To call total Price
   return;
   }
    this.secondTableData.push({
    itemName: data.itemName,
    rate:data.retailRate,
    Quantity: 1,
    retailRate: data.retailRate,
   })

   this.getColumnTotal();
  }

   // to calculate total amount
   getColumnTotal() {
   const { Quantity, Price } = this.secondTableData.reduce((acc, item) => 
     {
   acc.Quantity += item.Quantity;
   acc.Price += item.retailRate;
   return acc;
   }, {
   Quantity: 0,
   Price: 0
  });
  this.totalQuantity = Quantity;
  this.totalPrice = Price;
  }

Receive.html: 这是我要在数组中显示数据的代码

我想将这些变量(secondTableData、totalQuantity、TotalPrice...)推送到接收组件中,并希望以表格形式显示。

<table class="table table-bordered table-sm">
  <thead>
    <tr>
        <th>SN</th>
        <th>Product</th>
        <th>Unit</th>
        <th>Price</th>
        <th>Total</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let recData of myData;let i = index">  <!--i want to display here -->
        <td>{{i+1}}</td>
        <td>{{recData.itemName}}</td>
        <td>{{recData.Quantity}}</td>
        <td>{{recData.retailRate}}</td>
        <td></td>
        
    </tr>
    <tr class="small" style="height: 10px;">
        <td colspan="3" style="border: none;"></td>
        <td>Gross Amount:</td>
        <td>1100</td>
    </tr>
    <tr class="small">
        <td colspan="3" style="border: none;"></td>
        <td>Discount:</td>
        <td>100</td>
    </tr>
    <tr class="small">
        <td colspan="3" style="border: none;"></td>
        <td>VAT</td>
        <td>30</td>
     </tr>
     <tr class="small">
        <td colspan="3" style="border: none;"></td>
        <td>Net Amont</td>
        <td>1030</td>
      </tr>
    </tbody>
</table>

【问题讨论】:

    标签: angular angular-ui-router angular9


    【解决方案1】:

    您可以创建一个包含您想要的所有内容的传输对象(如果您希望使用单个调用发送所有变量):

    const tData = this.secondTableData; variable
    const t = this.totalPrice;
    const d = this.totalQuantity;
    
    const obj = {tData, t, d};
        
    this.dataShareService.onPushTable(obj);
    

    那么为您服务:

    @Injectable({providedIn: 'root'}) 
    export class DataShareService {
      private yourData;
    
      onPushTable(obj) {
        this.yourData = obj;
      }
    
      getYourData() {
        return this.yourData;
      }
    }
    

    在你的组件中:

    recDataFromService() {
      this.myData = this.dataShareService.getYourData();
    }
    

    [更新每条评论]

    上述答案完全没有错 => 没有更多信息,我认为您只是试图在错误的位置/时刻获取数据。为避免此问题,您应该在服务中采用响应式方法:

    @Injectable({providedIn: 'root'}) 
    export class DataShareService {
      private _yourData$: BehaviorSubject<{tData:any[];t:number;d:number}> =
          new BehaviorSubject<{tData:any[];t:number;d:number}>({tData:[],t:0,d:0});
    
      onPushTable(obj) {
        this._yourData$.next(obj ? obj : {tData:[],t:0,d:0});
        // if you're using ts >= 3.9.x you can use:
        // this._yourData$.next(obj??{tData:[],t:0,d:0});
      }
    
      getYourData$(): Observable<{tData:any[];t:number;d:number}> {
        return this._yourData$.asObservable();
      }
    }
    

    关于接收组件的打字稿文件:

    _fromFirstComponent$: Observable<{tData:any[];t:number;d:number}> = 
        this._dataService.getYourData$();
    
    constructor(private _dataService: DataShareService){}
    

    并且,在您的接收模板中:

    ...
    <tbody>
        <tr *ngFor="let recData of (_fromFirstComponent$ | async)?.tData;let i = index">  <!--i want to display here -->
            <td>{{i+1}}</td>
            <td>{{recData.itemName}}</td>
            <td>{{recData.Quantity}}</td>
    ...
    

    【讨论】:

    • 得到错误:找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays。当我在 show.Html 中使用 myData 时显示此错误。
    • 这与您的特定对象类型有关,我在回答中没有处理。您必须提供更多信息才能获得更完整的答案。基本上错误是告诉你你正在传递一些不可迭代的东西给ngFor
    • 那我如何在 ngFor 中使用 myData?变量 secondTableData 包含 itemName、Price、totalprice 等等。你有什么答案吗?
    • 是数组吗?将数据样本放入您的问题中。
    • 看看,让我知道它是否有效。如果没有,请在onPushTable(obj) 中添加console.log,以显示通过obj 参数传递的内容。
    【解决方案2】:

    如果您将服务注入到其他组件中,则存储在您的服务中的任何变量都将在其他组件中可见。

    在您的情况下,在 onPushData 上,将您想要的所有内容存储在您的服务中。我不知道你想要什么,但会是这样的:

    onPushData(){                          
      let tData = this.secondTableData;
      let t = this.totalPrice;          
      let d = this.totalPrice;           
      this.dataShareService.onPushTable(tData, t, d);
      this.routerService.navigate(['./billprint'])
    }
    

    确保您的服务接收所有三个变量并将其存储在其上(例如,在您的服务上创建这些变量 tdata、t 和 d 并在 onPushTable 上获取它。

    所以,在第二个组件构造函数中注入你的服务:

    constructor(private myService:MyService)
    

    然后,它将在以下时间可用:

    console.log(this.myService.tData);
    console.log(this.myService.t);
    console.log(this.myService.d);
    

    【讨论】:

      【解决方案3】:

      为您服务:

      @Injectable({
        providedIn: 'root'
      }) 
      
      export class DataShareService {
        private subject = new Subject<any>();
      
        onPushTable(data) {
          this.subject.next(data);
        }
      
        getData(): Observable<any> {
          return this.subject.asObservable();
        }
      }
      

      在你的sendComponent:

      this.dataShareService.onPushTable({tData, t, d});
      

      在你的receiveComponent:

      this.service.getData().subscribe(data => this.data = data);
      

      然后在您的 HTML 模板中使用 data 字段,例如:

      <div>{{data.t}}</div>
      <div>{{data.d}}</div>
      <tr *ngFor="let rec of data.tData;let i = index">
         <td>{{i+1}}</td>
         <td>{{rec.itemName}}</td>
         <td>{{rec.Quantity}}</td>
         <td>{{rec.retailRate}}</td>
      </tr>
      

      【讨论】:

      • 感谢您的回答,但它对我不起作用..
      猜你喜欢
      • 2017-05-06
      • 2017-11-25
      • 2018-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多