Tips for managing numerous nested subscriptions

Looking to extract the id parameter from the route, fetch the corresponding task, and then its parent if applicable.

    
    Angular CLI: 7.1.4
    Node: 11.6.0
    OS: linux x64
    Angular: 7.1.4
    @angular-devkit/architect         0.11.4
    @angular-devkit/build-angular     0.11.4
    @angular-devkit/build-optimizer   0.11.4
   

Task service:

   
    import { ITask } from '@task/interfaces/task';
    ...
    export class TaskService {
      constructor(private _http: HttpClient) {}
    ...
      get_task(id: number) {
        return this._http.get<ITask>(\`http://127.0.0.1:8000/api/task/${id}\`);
      }

In my component:
Obtaining one task that already has 2 subscriptions


    this._route.params.subscribe((params: Params) => {
      this._task_service
        .get_task(params['id'])
        .subscribe(
          (data: ITask) => { this.task = data; },
          err => { this._log.log('error while fetching task ', err); }
        );
    });

I want to

this._route.params   
get_task(params['id'])
if `task.parent` get parent task 

After hours of research and multiple failed attempts
flatMap().subscribe(...) // Type 'Subscription' is not assignable to type 'ObservableInput<{}>'

Despite reading numerous posts online, I'm still confused.
Can someone provide an explanation and example on how to achieve this?

update

console.log( 
  'type ',
   typeof this._task_service.get_task(2),
   this._task_service.get_task(2)
);

Result obtained:

type  object 
{…}
​_isScalar: false
​operator: {…}
  project: function request()
​​  thisArg: undefined
​​  __proto__: Object { call: call(), … }
​source: {…}
  ​​_isScalar: false
  ​​operator: {…}
    ​​​predicate: function
./node_modules/@angular/common/fesm5/http.js/HttpClient.prototype.request/res$<()
    ​​​thisArg: undefined
    ​​​__proto__: Object { call: call(), … }
​​    source: Object { _isScalar: false, source: {…}, operator: {…} }
    ​​__proto__: Object { lift: lift(), subscribe: subscribe(), _trySubscribe: 
  d_trySubscribe(), … }
__proto__: Object { lift: lift(), subscribe: subscribe(), _trySubscribe: _trySubscribe(), … }

Answer №1

if you implement this, let me know how it goes since I am unable to test your code personally

const subscription = this._route.params.pipe(
  switchMap((params: Params) => combineLatest([
    this._task_service.parentFetchRequest(), // replace with appropriate parent fetch request 
    this._task_service.get_task(params['id'])
    ])
  )
  .subscribe(
    ([dataOfParent : ParentType, data: ITask]) => { 
      this.task = data; 
      this.parentTask = dataOfParent
      },
    err => { this._log.log('error while fetching task ', err); }
  );

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

Swapping elements with drag and drop in Angular 7

I'm experimenting with the new Angular 7 CDK Drag and drop feature to rearrange a list of items. However, I haven't been able to find an option to swap elements - most of the examples focus on sorting elements instead. Check out this example on ...

Employing strict mode, albeit with certain exceptions

When using the compiler strict mode ("strict": true), errors occur for my models that are structured like this: @Entity class MyModel { @Column() public name: string; @Column() public email: string; ... } The specific errors enc ...

TypeScript: creating an interface property that relies on the value of another

Is it feasible to have an interface property that relies on another? For instance, consider the following: const object = { foo: 'hello', bar: { hello: '123', }, } I wish to ensure that the key in bar corresponds to the value of f ...

Leveraging Promise in conjunction with async/await

As I venture into the world of async/await in TypeScript, I find myself pondering a few questions. Specifically, I have been working on a function to extract an ArrayBuffer from a Blob. async function readAsArrayBuffer(blob: Blob): Promise<ArrayBuffer& ...

Having trouble compiling a Vue.js application with TypeScript project references?

I'm exploring the implementation of Typescript project references to develop a Vue application within a monorepo. The current structure of my projects is outlined below: client/ package.json tsconfig.json src/ ... server/ package.json t ...

The announcement will not be made as a result of the utilization of a private name

I've been working on transitioning a project to TypeScript, and while most of the setup is done, I'm struggling with the final steps. My goal is to use this TypeScript project in a regular JavaScript project, so I understand that I need to genera ...

How can we effectively test arrow functions in unit tests for Angular development?

this.function = () => { -- code statements go here -- } I am looking to write jasmine unit tests in Angular for the function above. Any suggestions on how to achieve this? it("should call service",()=>{ // I want to invoke the arrow funct ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

Data types for keys and values in TypeScript

interface A { a?: number }; interface B { a?: string }; function replicate< Source extends object, Destination extends { [key in keyof Source]?: (1) } >( source: Source, key: keyof Source, destination: Destination, converter: ...

Determining the type of <this> in an Object extension method using TypeScript

I am attempting to incorporate a functionality similar to the let scope function found in Kotlin into TypeScript. My current strategy involves using declaration merging with the Object interface. While this approach generally works, I find myself missing ...

What is the process for importing files with nested namespaces in TypeScript?

Currently, I am in the process of transitioning an established Node.js project into a fully TypeScript-based system. In the past, there was a static Sql class which contained sub-objects with MySQL helper functions. For instance, you could access functions ...

Angular - Keeping component data in sync with service updates

Within my Angular application, I have several components utilized in an NgFor loop which all rely on a common service. My goal is to create a system where if one component alters a value within the shared service, that updated value will automatically pro ...

When a 401 error occurs, Angular's HttpClient subscribe method fails to capture the error

Something odd is happening with my code. Within my service, I have a simple httpClient get method. When the API responds with a status of 401, I expect it to trigger an error... but it doesn't. Instead, only 'complete' appears in the console ...

What is the reason behind the ability to assign any single parameter function to the type `(val: never) => void` in TypeScript?

Take a look at the code snippet below interface Fn { (val: never): void } const fn1: Fn = () => {} const fn2: Fn = (val: number) => {} const fn3: Fn = (val: { canBeAnyThing: string }) => {} Despite the lack of errors, I find it puzzling. For ...

Tips for validating Enum Strings using the newest version of Joi?

Is there a way to validate Enum String? In the past, I followed this advice from: https://github.com/hapijs/joi/issues/1449 enum UserRole { Admin = 'admin', Staff = 'staff' } const validator = { create: Joi.object().keys({ ...

Issue with Spring Boot project not updating data from database

Recently, I have been delving into a full stack application project using Angular and Spring Boot for the first time. Following a comprehensive tutorial has guided me through this journey. Starting with a project downloaded from , I included various depen ...

The swipe motion will be executed two times

By pressing the Circle button, the Box will shift to the right and vanish from view. Further details (FW/tool version, etc.) react scss Typescript framer-motion import "./style.scss"; import React, { FunctionComponent, useState } from &q ...

What does the "start" script do in the package.json file for Angular 2 when running "concurrent "npm run tsc:w" "npm run lite"" command?

What is the purpose of concurrent in this code snippet? "scripts": { "tsc": "tsc", "tsc:w": "tsc -w", "lite": "lite-server", "start": "Concurrent npm run tsc:w npm run lite" } ...

typescript undefined subscription to observable

After making an http request to fetch some data, I am facing issues in displaying it as intended. The dropdown select for entriesPerPage, and the left and right cursors for switching page in pagination are working fine. However, upon switching a page, I en ...

Using ngrx to automatically update data upon subscription

Background The technology stack I am using for my application includes Angular 4.x, ngrx 4.x, and rxjs 5.4.x. Data is retrieved from a websocket as well as a RESTful API in order to share it between multiple components through ngrx. Currently, data is ref ...