Reputation: 7115
I recently updated my version of angular using ng update
and when running ng lint
I am getting the error create is deprecated: use new Observable() instead
this.data$ = Observable.create(t => {
t.next(this.model);
t.complete();
});
What is the syntax for new observable?
Upvotes: 55
Views: 44243
Reputation: 7682
Pretty simple
this.data$ = new Observable((observer: Observer) => {
observer.next();
observer.complete();
});
this.data$ = new Observable<void>((observer) => {
observer.next();
observer.complete();
});
Instead of void
you can put any type your observable is supposed to emit. Observer's next
value type will be inferred for the callback.
Upvotes: 88
Reputation: 21
on NgOnInt create custom observable like this
ngOnInit() {
const customObservable = new Observable((observer: Observer<object>){
observer.next(this.modal);
observer.complete();
})
subscribe it
this.customSubscription = customObservable.subscribe((data) => {
// logic goes here
})
}
later on, in ngOnDestroy unsubscribe it
ngOnDestroy() {
this.customSubscription.unsubscribe();
}
Upvotes: 2
Reputation: 4494
In 2021 it is changed.
new Observable((observer: Observer<object>) => {
observer.next(data);
});
instead of
new Observable((observer: Observer) => {
observer.next();
observer.complete();
});
Upvotes: 17
Reputation: 1999
observableSubscription: Subscription;
Creating Custom Observable
const observer = new Observable((observer: Observer) => {
observer.next();
observer.error();
observer.complete();
});
Subscribing To Custom Observable
this.observableSubscription = observer.subscribe((data:any) => {
console.log(data);
})
Unsubscribing
this.observableSubscription.unsubscribe();
Upvotes: 7