首页 > 解决方案 > behaviorSubject 订阅时返回 [object][object]

问题描述

我正在使用银行 API 进行支付。银行想要回应的是他 Ban Pay JavaScript 将在顶部框架中执行 HTTP 重定向到 completeUrl。我应该给银行api发送他们的response.in我的app.component.ts的url是什么completeUrl

          this.http.post("BankEndURL",quote,).subscribe(s=>{
    //here i get quote 
      this.newpay=s;
      
      //here im passing the paymentID to my service in angular to store there,because 
            at the end of the transaction ,if its successful i need it to show the transaction data
            this.dataService.setData(s);
       //here i send a quote to backend to give me a bankurl with payment data
       this.http.post("SecondBakednURL",this.newpay).subscribe(s=>{
     
         this.payaddress= s['reDirectAuthorizationHref'];
         //here i open the url to redirect the user to the payment portal
          window.open(this.payaddress);

这是我创建的服务:

public sharedData = new BehaviorSubject<any>(null);

构造函数(){}

  getData(){   
  return this.sharedData;
       }

setData(data:any){
this.sharedData.next(data);
}

这是我的接收器组件,一旦交易成功,银行将点击它,我将显示用户的交易数据

        constructor(private dataService:DataService) {}

      ngOnInit(): void {
        this.dataService.getData().pipe(
          filter(data => !!data)
        ).subscribe(data => {
          alert(data)
        });

但这里的数据返回 null

标签: javascriptangular

解决方案


在这种情况下,getSharedData()返回行为主体本身,因此在这种情况下,明智的做法是订阅它,以便接收您在调用时发出的数据setData

在接收器组件中:

ngOnInit(): void {
  this.dataService.getData().pipe(
    filter(data => !!data)
  ).subscribe(data => {
    alert(data)
  });
}

推荐阅读