简体   繁体   中英

Issue in fetching data from Subscriber Angular

Hi I am new to angular and was learning the concepts of observable and Subject. What I understood was that observable are event emitters to which other code can subscribe to, and Subject can both both subscribe and emit data. I tried the below code where I check if time in milliseconds is even or not and based on that I am emitting success and failure. Basically I have created a random method for success and failure. The problem is whenever there is an error the control moves to error block but it never prints success or goes to success block. I am not sure what am I doing wrong. Please let me know also if you can point me to any blog or documentation which help in removing the gaps in my knowledge. Thanks in advance.

test() {
   const test_subject = new Subject<any>();
   var x = new Date();
   console.log(x.getMilliseconds());
   if (x.getMilliseconds() % 2) {
     //debugger;
     test_subject.next(true)
   } else {
     //debugger;
     test_subject.error(false);
   }
   return test_subject.asObservable();
 }


   callSubscription() {
       this.appService.test().
           subscribe(data => {
               console.log("success");
           }, error => {
               console.log("fail");
           });
   }

From the RxJS documentation:

In an Observable Execution, zero to infinite Next notifications may be delivered. If either an Error or Complete notification is delivered, then nothing else can be delivered afterwards.

https://rxjs-dev.firebaseapp.com/guide/observable

This means that if you ever call error() or complete() you cannot call next() anymore unless you implement error handling or recreate your observable.

Your code never logs success because you call test_subject.next(true) before your subscribe to the Subject.

If you subscribe to a Subject you will only receive the values published from then onwards but not any previously published values. Though you will still receive the error when you subscribe to a Subject after it errored.

To log emitted values in the success callback either call next after you subscribe or use a BehaviorSubject or ReplaySubject. See: Subject vs BehaviorSubject vs ReplaySubject in Angular

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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