【问题标题】:How to pass data from child component to parent component in Angular4如何在Angular4中将数据从子组件传递到父组件
【发布时间】:2018-08-25 07:36:22
【问题描述】:

我正在使用 Angular4 应用程序。在此我想将数据从子组件传递到父组件。让我解释一下细节...

app.component.html

代码...

 <div class="col-3">
          <br>
          <form class="form-inline">
            <div class="input-group">
              <div class="input-group-prepend">
                <span class="input-group-text" id="basic-addon1">
                    <i class="fas fa-shopping-bag text-primary" style="font-size:40px"></i>
                </span>
              </div>
              <input type="text" class="form-control bg-white"  placeholder="My Cart" value="  My Cart  {{totalcartval}} Item(s)" readonly >  
            
            </div>
          </form>
        </div>

我的购物车.component.html

代码...

 import { Component,EventEmitter,Output } from '@angular/core';
    import { Router } from '@angular/router';
    import { HttpClient } from '@angular/common/http';
    import { SessionStorageService,SessionStorage } from 'angular-web-storage';
    
    
    @Component({
      selector: 'app-my-cart',
      templateUrl: './my-cart.component.html',
      styleUrls: ['./my-cart.component.css'],
      outputs :['ChildEvent']
    })
    
    export class MyCartComponent  {

    public sendRecord(Totalcartval : number ) {  
          this.http.get('http://freegeoip.net/json/?callback')
                     .subscribe(
                        data => this.saveIP(data['ip'],Totalcartval),
                        error => console.error(error)
                     );
        }
        saveIP(address: string,cartval :number) {
          this.http.get(`http://localhost:57036/api/data/CartCount/?IP_ADDRESS=${address}&ITEM_QTY=${cartval}&TIME=${this.fixedTimezone}`)
                   .subscribe(data => this.res = data['ITEM_QTY']);
      }  
    ngOnInit() {}
    }

当我添加一些数量并单击“添加到购物车”按钮时,数量会通过 API 传递到数据库进行存储,并在这一行得到响应(数量)

.subscribe(data => this.res = data['ITEM_QTY']);

现在我想从 my-cart.component.html 向 app.component.html 显示数量计数 ....当数据存储在 db 中时,响应回来了,我需要立即显示在父组件中计数,没有任何时间中断

我已经在 stackoverflow 中提到了一些例子,比如智利到父数据传递,但对我没有任何作用......

一些示例,例如子到父数据传递,需要在父组件中显示子组件,但在我的情况下,我不想在父组件中显示子组件,为什么因为如果我在购物车中添加了一些产品,我可以能够导航回我的父组件并在我的购物车中进一步添加其他产品...

Angular.. 有可能吗? 是的,意味着我怎样才能做到这一点......?

【问题讨论】:

  • 你可以使用状态管理技术来实现这个参考这个repository

标签: angular angular4-router angular4-httpclient


【解决方案1】:

使用共享服务在没有任何关系的组件之间共享数据。请阅读此link for more information。我使用 RxJS 的行为主题完成了 sample app in stackblitz 共享服务。

所有组件都可以访问和更改同一消息实例。

read through this link to know more about BehaviorSubject.

共享服务

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject<string>("default message");
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

【讨论】:

    【解决方案2】:

    我没有在您提供的 HTML 中看到您的购物车组件(而且我看不到图像),但是如果您确实有父子关系,那么您可以使用它来将数据从子节点传递到父母。

    在孩子身上

    constructor(@Host() parent: ParentComponent) {}
    

    现在,您可以使用任何您想传递的数据。

    例如

    this.parent['bridge'] = data; // If you don't want to declare a variable in the parent
    this.parent.doSomething(); // Calling a function i the parent
    this.parent.myVar = data; // If you have declared a variable in the parent
    

    【讨论】:

      【解决方案3】:

      我最近也在为网站创建购物车。为此,我没有在父组件和子组件之间传递数据,而是通过服务在组件之间传递数据。我通过表单将产品存储在购物车中.

      对于视图:

      <div class="products" *ngFor= "let product of Object.values(getItemsFromCartService()) ">
              <div class="product">
                <img [src]="product['imgURL']" [alt]="product.productSelected">
                <h4>{{product.productSelected}}</h4>
              </div>
              <div class="quantity">
                Qty.
                  <input #qty (blur)="updateQuantity(product, qty.value)" type="number" name="Quantity" [value]="product.Quantity" class="form-control">
              </div>
              <span class="glyphicon glyphicon-trash" (click)="removeItem(product.productSelected)"></span>
              <div class="productQtnPrice">
                    <h4 class="totalPrice"><i class="fa fa-inr"></i> {{product.totalPrice}} </h4>
              </div>
          </div>
      

      我已使用 blur 事件来更新产品的数量。你可以用同样的方法绑定到你的+-

      在打字稿中:

      getItemsFromCartService() {
          this.totalItemsInCart = this._cartService.getAllItems();
          this.setItemDetails();
          console.log(this.totalItemsInCart);
          return this.totalItemsInCart;
      }
      
      updateQuantity(product, newQuantity) {
              console.log("Updating quantity");
              this._cartService.updateQuantity(product, newQuantity);
          }
      removeItem(productName) {
              this._cartService.removeItem(productName);
          }
      

      【讨论】:

        【解决方案4】:
        1. 使用输入绑定将数据从父级传递给子级。 @Input()/@Input(别名)。 例如,@Input() hero: Hero;

        2. 使用 setter 拦截输入属性更改。使用输入属性设置器 拦截并根据父级的值采取行动。 例如,

          @Input() set name(name1: string) { this._name = (name1 && name1.trim()) || '<no name set>’; }

          例子,

          @Input() set age(ageNum: number) { this._age = (ageNum) || '<no age set>’; }

          &lt;app-name-child *ngFor="let personName of names" [name]=“personName“ [age]=“personage”&gt;&lt;/app-name-child&gt;

        3. 父母监听子事件。 子组件公开一个 EventEmitter 属性,当 有事情发生。 父级绑定到该事件属性并对这些事件作出反应。 例如,

          @Output() voted = new EventEmitter<boolean>();
          (voted)="onVoted($event)"

        【讨论】:

          猜你喜欢
          • 2018-02-15
          • 2018-02-12
          • 2018-05-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-27
          • 2017-04-20
          相关资源
          最近更新 更多