Angular: create is deprecated: use new Observable() instead
27,591
Solution 1
In 2021 it is changed.
new Observable((observer: Observer<object>) => {
observer.next(data);
});
instead of
new Observable((observer: Observer) => {
observer.next();
observer.complete();
});
Solution 2
Pretty simple
this.data$ = new Observable((observer: Observer) => {
observer.next();
observer.complete();
});
Solution 3
Or you can use just
this.data$ = of(this.model);
Solution 4
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();
Solution 5
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();
}
Author by
mruanova
Updated on November 24, 2021Comments
-
mruanova over 2 years
I recently updated my version of angular using
ng update
and when runningng 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?
-
Admin about 5 yearsYou also should be able to use
of()
-
Sergey about 5 years@OneLunchMan it's not the same. If you use
of()
it just emits values. However,of()
is not as capable as creating an Observable. There you can place a complicated logic -
Admin about 5 yearsGotcha, so the difference between needing more complex logic and not-
-
Sergey about 5 years@OneLunchMan Not that simple :). When you are using
of
you are producing.next
with values, however if you create an observable you can react on events and then pass some data to the subscribers as well as you could count these subscribers etc. -
Anton almost 4 yearsI am sorry, do i understand correctly ? Observable is an object we observe. Observe or sometimes called subscriber is something that overlook our observable and react to it's next/error/complete states. If yes, why would u then make a const variable with a name observer that new Observable returns. It kinda mess logic up.
-
beebus over 3 yearsIf "Observer" gives you a TS2314 Generic type 'Observer' error, try replacing it with "any" or "Observer<any>".