Ending subscription to an observable in Angular

Whenever I press a button, I receive information from a server about a specific vehicle by subscribing to an observable. If I press the same button again, I want to unsubscribe from the current "vehicleDetail" data that I'm viewing (to prevent memory leaks) so that I can inspect the new data of another vehicle.

I have a VehicleDetail class with the following properties:

export class VehicleDetail {
  id: number;
  name: string;
  alarm: Alarms[] | null;
  signalinfo: SignalInfo[];
  position: Position | null;
}

This is the code in my .service.ts file:

    getVehicleDetail(id: number): Observable<VehicleDetail> {
        const url = `${this.vehiclesUrl}/${id}/${'detail'}`;
        return this.http.get<VehicleDetail>(url).pipe(
          tap(_ => this.log(`fetched vehicle detail id=${id}`)),
          catchError(this.handleError<VehicleDetail>(`getVehicledetail id=${id}`))
        );
      }

And here's what I have in my .component.ts file:

import { Component, OnInit } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import * as Leaflet from 'leaflet';

import { VehicleService } from '../vehicle.services';
import { VehicleDetail } from '../models/vehicle-detail';

.........

vehicleDetail: VehicleDetail;
private unsubscribe$ = new Subject();

.........



  getVehicleDetail(): Observable<VehicleDetail> {
    const details = this.vehicleService
      .getVehicleDetail(this.vehicleService.vehicleId);

    details.takeUntil(this.unsubscribe$).subscribe(data => {
      this.vehicleDetail = data;
    });
    return details;
  }

updateInfo(item): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
    this.vehicleService.vehicleId = item;
    console.log(this.vehicleService.vehicleId);
    this.getVehicleDetail().takeUntil(this.unsubscribe$).subscribe(() => {
      if (this.vehicleDetail.position) {
        this.setMap();
        return;
      }
      this.map.flyTo(new Leaflet.LatLng(50.7089, 10.9746), 4, {
        animate: true,
        duration: 4
      });
    });
  }

The error message related to 'takeUntil' states:

Error TS2339: Property 'takeUntil' does not exist on type 'Observable'.

What could be the issue here?

Answer №1

When you make an HTTP request without creating a socket, there is no need to unsubscribe from the observable as it automatically finalizes to a completed state. Have you considered calling the service directly from the updateInfo function with the received id as a parameter?

updateInfo(vehicleId: number): void {
    this.vehicleService.getVehicleDetail(vehicleId)
     .subscribe((data) => {
       this.vehicleDetail = data;
       if (this.vehicleDetail.position) {
         this.setMap();
         return;
       }
       this.map.flyTo(new Leaflet.LatLng(50.7089, 10.9746), 4, {
         animate: true,
         duration: 4
       });
     });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Upon calling set() on Map, the object returned does not conform to a Map data structure

I've been exploring the transition to using immutable.js for managing states: class Register extends Component<{}, Map<string, string>> { state = Map<string, string>(); onInputValueChange(e) { const { name, value } ...

The Angular project encounters a failure when attempting to run 'ng serve,' resulting in an emitted 'error' event on the worker

Resolved Issue - Update: It appears that the problem was due to an error in my CSS code: Previous: .title & .smaller { color: $dark-blue; font-family: "Roboto"; font-size: 20px; font-weight: 600; width: fit-content; margin: 0; ...

What is the alternative method to lazy load Angular modules without using the CLI?

I am on the hunt for information regarding a specific use case that seems to elude me in all my searches. If you know of its existence, please point me in the right direction. My goal is to implement lazy loading of Angular modules, specifically using Ang ...

Is there a proper way to supply createContext with a default value object that includes functions?

As I was creating my context, I set an initial state and passed the necessary functions for useContext. Although this method is functional, I'm concerned it may present challenges in larger projects. Does anyone have suggestions for a more efficient a ...

What is the best way to transform JavaScript into TypeScript?

I've been researching TypeScript extensively, but I'm still unsure about what type I should set for elements X and Y. Can someone help me understand how I can convert this code to TS? Thank you in advance for your assistance. const x = document.g ...

Ensuring Code Coverage with Husky in Angular 8 Pre-Commit Hooks

I am currently working on an angular 8 project and I want to implement a rule where the user can only commit if a certain percentage of code coverage passes. Currently, I am using NX Workspace and Husky to run Linting before committing. In addition to thi ...

Console.log is displaying array as [object Object] when utilizing Typescript

When working with an object in typescript called "obj," I encountered a strange behavior. Initially, when I ran the console.log(obj); command, the output in the terminal console was displayed as [object Object]. However, after wrapping it in JSON.stringify ...

What is the best way to showcase custom formatted nested keys within swimlane ngx-datatable?

<ngx-datatable [rows]="services" [columns]="columns"> </ngx-datatable> One way to display nested data is by using the following code snippet: { prop: order.product.price } If you want to display a custom calculation in a row, such as a ...

There was an unhandled exception that occurred due to a missing file or directory with the lstat error on 'D:a1s ode_modulesquill'

ngx-quill is causing issues in production, any suggestions? I am currently using "ngx-quill": "^13.4.0", but it is unable to find Quill on my server even though it works locally. The problem persists in the pipeline... An unhandled exception has occurred ...

Typescript: Convert Generics to a String Format

Is there a way for me to return a generic type as a string in this function? const actionName = <P extends string>(path: P) => <A extends string>(action: A): string => `${path}/${action}`; const path = actionName('filter'); con ...

Creating anchor links with #id that function correctly in an Angular project can sometimes be challenging

My backend markdown compiler generates the HTML content, and I need Angular to retrieve data from the server, dynamically render the content, and display it. An example of the mock markdown content is: <h1 id="test1">Test 1<a href="#test1" title ...

Error [ERR_MODULE_NOT_FOUND]: Unable to locate the specified module (TypeScript/TypeOrm)

I'm encountering an issue where the content of my database is not being printed when using an entity with TypeScript/TypeOrm. Here's the code I have: Main file : import { createConnection, getManager ,getConnectionOptions } from 'typeorm&a ...

Loop through an icon in Angular 2 until a specific condition is met

Currently, I am in the process of developing my portfolio website using Angular 2 and I want to incorporate a skill matrix. For testing purposes, I am using a square provided by font-awesome as an example. <tbody *ngFor="let skill of skills"> <tr ...

The HttpParams are reluctant to be established

Working with Angular 8, I am attempting to assign an HttpParam using the provided code snippet and observing the outcome on the final line. let newParams = new HttpParams(); newParams.set('ordering', 'name'); console.log('getting: ...

Troubleshooting date errors in react-datepicker using hookstate and Next.js

Exploring a page in the realm of nextjs: import type { NextPage } from "next"; import DatePicker from "react-datepicker"; import { useState as useStateHook } from "@hookstate/core"; import { useState as useStateReact } from &q ...

Encountering the "ExpressionChangedAfterItHasBeenCheckedError" in Angular 2

As I try to fill in multiple rows within a table that I've created, the table gets populated successfully. However, an error message pops up: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous valu ...

Configuring TypeScript for Firefox to recognize specific types such as browser.storage

As per the documentation from Mozilla, I should be able to utilize browser.storage.sync.get in my extension. However, I am encountering some challenges in getting TypeScript to recognize that I can use browser. I have attempted the following (which has wo ...

Utilize Sequelize's cascade feature within your application

I'm currently building a web application using sequelize and typescript. In my database, I have three tables: WfProjectObject, which is connected to WfProject, and WfStep, also linked to WfProject. My goal is to include WfStep when querying WfProject ...

Generating dynamic components using React and TypeScript

Creating a multi-step form using a set of components can be tricky. One approach is to compile all the components into an array and then use the map() method to render them in sequence. const stepComponents = [ <SelectCoach/>, <SelectDate/> ...

Troubleshooting resizing issues with elements in Angular

Currently, I am utilizing 'ResizableModule' in angular9 to make my div resizable. However, when I release the div, it reverts back to its original size. I have used the following package: https://www.npmjs.com/package/angular-resize-element. Ho ...