Reputation: 15054
I am able to create an Observable in my angular component in below mentioned way
...
...
import { Observable } from 'rxjs/Observable';
..
...
let observable = new Observable( function subscribe(observer) {
observer.next(1);
observer.next(2);
observer.next(3);
observer.next(4);
setTimeout(() => {observer.next(5); },9000);
});
But am not aware of how to create a Subject , can some one provide an example for the same ?
Upvotes: 12
Views: 28083
Reputation: 1851
You can do it by following code
import { BehaviorSubject } from 'rxjs';
subject = new BehaviorSubject<string>("");
observer = this.subject.asObservable();
//TO FIRE NEXT EVENT
this.subject.next("My next value");
// TO SUBSCRIBE EVENT
this.observer.subscribe({
next : (value)=>{
console.log(value); // will return My next value
}
});
Upvotes: 1
Reputation: 40647
Here's a plunker: http://plnkr.co/edit/jLtFLjWrvHGI0ZPHl10B?p=preview
import {Subject} from 'rxjs/Subject'; // from 'rxjs'; for the newer rxjs versions
@Injectable()
export class MyService {
public invokeEvent:Subject<any> = new Subject();
constructor() {}
}
subscribe to it like an observable:
constructor(private _myService: MyService) {
this._myService.invokeEvent.subscribe((value) => {
console.log(value);
});
}
and push values to it like an observable again with next
ngAfterViewInit(){
this._myService.invokeEvent.next(1);
}
Upvotes: 14
Reputation: 77482
Using Rx.Subject
with Angular it is no different from using it without Angular, the main principle is the same, look at the example below
const subject = new Rx.Subject();
const subscription = subject.subscribe(
(data) => console.log(data),
(err) => console.log(err),
() => console.log('Completed')
);
subject.next(1);
subject.next(2);
subject.next(3);
subject.complete();
<script src="https://unpkg.com/@reactivex/[email protected]/dist/global/Rx.umd.js"></script>
You need to make new instance Rx.Subject
, then subscribe to it where you need to, and fire event.
Upvotes: 3