angular - 首次单击 Rxjs 时未将值发送到 Angular 中的其他组件

标签 angular rxjs

我正在尝试使用 Angular 2+ 中的 Rxjs 将 ProductId 从一个组件发送到另一个组件。所以当我第一次单击事件函数时,Rxjs sendFucntion 没有将 ProductId 发送到其他组件。但第二次点击它就出现了。

这是代码

Rxjs Class for handling send and get calls
      
 import {Subject} from 'rxjs';

 @Injectable({
 providedIn: 'root'
 })

export class MessengerService {
_Subject = new Subject;
 constructor() { }

   SendMessageWithData(MessageAndData){
      this._Subject.next(MessageAndData);
   }

  GetMessageWithData(){
      return this._Subject.asObservable();
   }
}

Component 1.ts
      SendProductId(_ProductId){
         //Here I am getting the Product id here successfully I cheecked it using console.log
        this._MessengerService.SendMessageWithData(_ProductId);
        this._Router.navigate(['viewProduct']);
    }


  Component2.ts
  ngOnInit(): void {

     //Setting the Local Storage
     this._MessengerService.GetMessageWithData().subscribe(docs=>{
         console.log(docs);
         this._EcommerceDataService.SetLocalStorageForProductId(docs);
     });
 }

现在这是我的代码逻辑。但它不适用于第一次单击功能,但在第一次单击后有效。请指导我问候

最佳答案

很可能第一个通知是在订阅之前发出的。 RxJS Subject 只会向已经订阅的观察者发出通知。您可以改为使用带有缓冲区 1 的 ReplaySubject

import { ReplaySubject } from 'rxjs';

export class MessengerService {
  _Subject = new ReplaySubject(1);

  constructor() { }

  SendMessageWithData(MessageAndData){
    this._Subject.next(MessageAndData);
  }

  GetMessageWithData() {
    return this._Subject.asObservable();
  }
}

关于angular - 首次单击 Rxjs 时未将值发送到 Angular 中的其他组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66748258/

相关文章:

typescript - RxJS 将 Observable<string[]> 转换为 Observable<string>

angular - 使用文件保护程序在 Angular4 中下载文件

angular - *ngFor 在某些值 [date] 更改时添加某些 div [date] 元素

angular - 如何在 angular2 的 div 的 contenteditable 上使用 [(ngModel)]?

javascript - 对主题使用 mergeMap() 会忽略我正在合并的可观察对象上的 takeWhile()

angular - 如何使用 Angular 中的 Observable 获取多个页面?

angular - Nativescript 的 AOT 编译成功 - 但仍然包含 `Compiler` 包?

javascript - 如何在 HTML 中显示 TypeScript 对象(Ionic/Firebase/Angular)

angular - 如何使用具有依赖于另一个选择器的参数的 ngrx 选择器

javascript - 为什么这种解构不起作用?