繁体   English   中英

不相关组件之间的角度通信

[英]Angular communication between unrelated components

我有两个不相关的组件CartComponent和CheckoutComponent。 我想将数据从CartComponent传递到CheckoutComponent。 为此,我创建了共享服务。

    export class CartService {
  private cartSubjectList = new Subject<Products[]>();
  currentSubjectList = this.cartSubjectList.asObservable();
  public cartCount = 0;
  constructor() {
    console.log('CartService log:', this.currentSubjectList);
   }

  setData(cartList: Products[]) {
    this.cartSubjectList.next(cartList);
  }
  getData() {
    return this.currentSubjectList;
  }
  getCartProducts(): Products[] {
    const products: Products[] = JSON.parse(localStorage.getItem('cart')) || [];
    return products;
   }

CartComponent中,我将数据设置为setData方法中的cartSubjectList。 调试

 export class CartComponent implements OnInit {

      cartProducts: Products[];
      constructor( private cartService: CartService) { }
      ngOnInit() {
        this.getCart();
      }

      getCart() {
      this.cartProducts = this.cartService.getCartProducts();
      this.cartService.setData(this.cartProducts);
      }
}

CheckoutComponent中,我想显示我的数组,但是我的checkoutProduct未定义。

 export class CheckoutComponent implements OnInit {

  checkoutProducts: Products[];
  constructor(private formBuilder: FormBuilder, private cartService: CartService) { }

  ngOnInit() {
    this.cartService.getData().subscribe( data => {
      this.checkoutProducts = data;
      console.log(this.checkoutProducts);
    });
  }
}

欢迎任何帮助或建议

这是因为您正在使用Subject 除非是ReplaySubjectBehaviorSubject否则Subject新订阅者将不会收到之前发出的任何内容。

我建议使用ReplaySubject ,缓冲区长度为1:

private cartSubjectList = new ReplaySubject<Products[]>(1);

进行新订阅时(通过CheckoutComponent ),它应立即收到先前的订阅。

您必须确保两个组件使用相同的服务实例。 在哪里提供服务? 如果这两个组件都在同一模块中,请在该模块中提供服务。 如果它们在不同的模块中,则仅在导入两个组件的模块的模块中提供服务。 AppModule通常是一个安全的选择。)

另外,使用Angular的6个以上版本,您可以直接从服务中设置提供的模块。 从提供服务的所有模块中删除该服务,然后尝试:

@Injectable({
    providedIn: 'root'
})

这应具有与仅在AppModule提供服务相同的结果。

我必须支持您的getCartProducts是一个异步调用-您进行get或返回observable,因此需要在subscription中发送值

getCart() {
  this.cartService.getCartProducts().subscribe(res=>{
     this.cartProducts =res;
     this.cartService.setData(this.cartProducts);
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM