![](/img/trans.png)
[英]Angular - Communication between unrelated components with return value
[英]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
。 除非是ReplaySubject
或BehaviorSubject
否则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.