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();
}
Share:
27,591
mruanova
Author by

mruanova

Updated on November 24, 2021

Comments

  • mruanova
    mruanova over 2 years

    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?

  • Admin
    Admin about 5 years
    You also should be able to use of()
  • Sergey
    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
    Admin about 5 years
    Gotcha, so the difference between needing more complex logic and not-
  • Sergey
    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
    Anton almost 4 years
    I 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
    beebus over 3 years
    If "Observer" gives you a TS2314 Generic type 'Observer' error, try replacing it with "any" or "Observer<any>".