0

The observable function is NOT http; the function must be local, but it needs to be subscribed. This is the best I could do based on online example:

export class AppComponent implements OnInit {
  title = 'Sample';
  message1 = '';

  observable = new Observable((subscriber) => {
    subscriber.next(1);
    subscriber.next(2);
    subscriber.next(3);
    setTimeout(() => {
      subscriber.next(4);
      subscriber.complete();
    }, 1000);
  });    


  constructor() {}

  ngOnInit() {
  }   

  public getUser() {
      this.observable.subscribe({
        next(x) {
          this.message1 = 'got value ' + x;  <--------------------------
        },
        error(err) {
          console.error('something wrong occurred: ' + err);
        },
        complete() {
          console.log('done');
        },
      });
      console.log('just after subscribe');
    }
}

The subscriber has no access to anything outside of itself (the message1 I show with arrows). Thoughts?

1 Answer 1

1

Have you looked at a Subject? A subject is both an observable and an observer and exposes it's next method.

const { Subject } = rxjs;

obs$ = new Subject();

obs$.subscribe(val => { console.log(val); });

obs$.next(1);
obs$.next(2);
obs$.next(3);
setTimeout(() => {
  obs$.next(4);
  obs$.complete();
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.8.0/rxjs.umd.min.js"></script>

There is also BehaviorSubject that stores the most recently emitted value for new subscribers and ReplaySubject that stores a buffer of emitted values.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.