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

The symbol 'router-outlet' is not recognized by the system

This new project utilizes Angular 13 for its implementation. One of the key updates is the addition of routing to the project, specifically in the file app-routing.module.ts. import { NgModule } from '@angular/core'; import {RouterModule, Routes ...

When using Playwright, there may arise a requirement to reuse a specific UUID that has been defined in one test within another

I have two separate tests running in parallel, each creating a different company in my test environment. However, I need to access the uuid of both companies in later tests. I am looking for a way to store these uuids so they can be used across all subseq ...

Ignoring TypeScript type errors in ts-jest is possible

Recently, I embarked on a journey to learn TypeScript and decided to test my skills by creating a simple app with jest unit testing (using ts-jest): Here is the code snippet for the 'simple app.ts' module: function greet(person: string): string ...

Choose an alternative following the start-up phase

I have been searching for solutions on various platforms, including Stack Overflow, but nothing seems to work for me. I am struggling with selecting the first option after initializing the box because currently it is choosing a blank option that is not eve ...

What is the best way to implement promise function in a JavaScript functional method such as forEach or reduce?

I have implemented a promise function in the following way: // WORK let res = {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc}; for (let i = 0; i < rv.copyDetailList.length; i ++) { const item = rv.copyDetailList[i]; ...

Error TS7053 occurs when an element is given an 'any' type because a 'string' expression is being used to index an 'Object' type

When attempting to post data directly using templateDrivenForm and retrieve data from Firebase, I encountered the following type error message. Here are the relevant parts of my code: // Posting data directly using submitButton from templateDrivenForm onC ...

Tips for integrating JavaScript libraries with TypeScript

I'm looking to add the 'react-keydown' module to my project, but I'm having trouble finding typings for it. Can someone guide me on how to integrate this module into my TypeScript project? ...

The test.ts file does not contain any type definitions

While I am able to successfully utilize my types in .ts files, I am facing difficulties in understanding why it's failing in .test.ts files, even though both files are located in the same folder. Check out the code in the .ts file below: https://i.s ...

Adjust the width of Google chart to 100% automatically when the page is resized in Angular version 4 or higher

My application has numerous responsive wrappers on the site, each predefined from an API and containing a Google chart. The problem is that when the page initially loads, the charts are rendered at a specific size, and resizing the window only affects the ...

Unable to retrieve the headers from the error response

When working with Angular 6, I encountered an issue where I couldn't retrieve the headers from an HTTP error response. Specifically, when the server responded with a status code of 401, additional headers were included in the error response. What is t ...

How to retrieve the NgModel Object within a component file using TypeScript

I am currently utilizing [(ngModel)] for two-way binding. The structure in HTML is as follows - <input type="text" [(ngModel)]="emailInput" #toemail="ngModel" [email]="true" [style.color]="toemail.invalid && toemail.touched ? &a ...

Arrange the list by first names in the array using Ionic 3

What is the process for arranging a list by firstName from an array? This is my code in my.ts file: initializeItems(){ this.items = [ { avatar: '../../assets/imgs/profile1.jpg', firstName:'Sterlian', lastName:'Victorian ...

Arranging an array in Angular 7 with various states and numbers

Looking to tackle this array sorting issue in Angular 7, the data is fetched from the API: "Products": [ { "ProductCode": "MC30180", "Description": "Description_1", "NationalCode": "N.C. 0965", "Pend ...

Despite my efforts to properly run, my angular component is still not being added to the angular module

After attempting to execute ng generate component elements/ElementsHome, I encountered a successful run; however, the terminal did not display the Updated file path as a hyperlink. Instead, it indicated that the component was not created within the module. ...

Prevent any angular text box from allowing just one special character

Hello, I am facing a requirement where I need to restrict users from inputting only one special character, which is ~. Below is the code snippet: <div class="form-input "> <input class="pass" [type]="'passw ...

Experience Next.js 13 with Chakra UI where you can enjoy Dark Mode without the annoying White Screen Flash or FOUC (flash of unstyled content)

Upon refreshing the page in my Next.js 13 /app folder application using Chakra UI, I notice a few things: A momentary white flash appears before switching to the dark theme. The internationalization and font settings momentarily revert to default before l ...

Switching the scope or zone in Angular when handling events external to Angular

Currently, I am utilizing an external library within my Angular 6 application that incorporates customizable event listeners. Specifically, I am employing flowchart.js, although similar issues may arise with other libraries. In the case of flowchart.js, i ...

In order to access the localStorage from a different component, a page refresh is required as it is

UPDATE: Just to clarify, this question is NOT duplicate of how to retrieve the value from localstorage. My scenario is unique and the issue lies with Angular itself rather than localStorage. I am currently developing an Angular7 application. In one of my ...

Reference ngFor for Input Validation Template

I'm currently facing an issue with validating input fields within a *ngFor loop. I am struggling to create unique template references for each input field. Basically, I need all input fields to be required on submit unless at least one of them is fill ...

Tips for extracting individual fields from a payload in Angular 8

How do I extract individual fields from the payload and bind them with HTML on a page? I am trying to retrieve the alphacode and countryname in Angular 8. This is my Component: this.table$ = this.productService.get(id) .map(actions => { c ...