Patrice
Patrice

Reputation: 19

Angular TS subscribe method is marked as deprecated but is working fine

I've written the function which shall everytime it is called get new data trough a service file.

The function looks like this:

onCarChange() {
 this.carService.getCarData(this.selectedCar).subscribe(
  async (response: CarData) => {
   if (response?.data === null) {
    this.showCarData = false;
   } else {
      this.showCarData = true;
   }
  },
  (error) => {
   this.showCarData = false
   console.error(error);
  }
};

My service.ts file looks like this:

getCarData(carId: string) {
 return this.http.get(API.carData.get(carId));
}

The function is working fine and as intended so no issues on that. But right now I'm trying to clean up my code and I've noticed that the subscribe method is crossed out and marked as deprecated. Does somebody know how to get rid of this? Do I need to reconstruct the function? And if yes what would it look like?

Upvotes: 0

Views: 1151

Answers (2)

Saidamir
Saidamir

Reputation: 328

The way you are using is deprecated. You can read more here.

.subscribe({
   next: () => { ... }, // (required) nextHandler
   error: () => { ... }, // (required) errorHandler
   complete: () => {.. }, // (optional) completeHandler
})

So in your case use :

onCarChange() {
 this.carService.getCarData(this.selectedCar).subscribe({
    next: async (response) => {
        if (response?.data === null) {
            this.showCarData = false;
        } else {
              this.showCarData = true;
        }
    }, 
    error: (err) => {
        this.showCarData = false
        console.error(err);
    }
  })
};

Upvotes: 1

Carles Ramos
Carles Ramos

Reputation: 354

You have to pass an observer object.

onCarChange() {
    this.carService.getCarData(this.selectedCar).subscribe({
        next: async (response) => {
            if (response?.data === null) {
                this.showCarData = false;
            } else {
                  this.showCarData = true;
            }
        }, error: (err) => {
            this.showCarData = false
            console.error(err);
        }
    });
};

Upvotes: 4

Related Questions