我正在尝试使用 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/