Hold off on utilizing information from a single observable until a later time

In my Angular component, I am working with the following code:

@Component({...})
export class ComponentOne implements OnDestroy, OnChanges {

  readonly myBehaviourSub = new BehaviorSubject<Observable<MY_CUSTOM_INTERFACE>>(NEVER);

  constructor(private readonly myService: MyService){}

  ngOnChanges(changes: SimpleChanges) {
    this.myBehaviourSub.next(
      this.myService.fetchSomeData(alpha, beta, gamma)// 'fetchSomeData' returns an observable with type MY_CUSTOM_INTERFACE
        .pipe(
          shareReplay({refCount: true, bufferSize: 1})
         )
    );
      
  }

}

The structure of MyService resembles this:

@Injectable({providedIn: 'root'})
export class MyService {

  fetchSomeData(alpha, beta, gamma) : Observable<MY_CUSTOM_INTERFACE> {
     ...
     return obs<MY_CUSTOM_INTERFACE>;
  }

  fetchNewValuesForAlpha() : Observable<ALPHA_INTERFACE> {
     ...
     return obs<ALPHA_INTERFACE>
  }

}

I have a requirement to retrieve new values for "alpha" by first calling "fetchNewValuesForAlpha" before passing it to "fetchSomeData". Here is what I attempted:

@Component({...})
export class ComponentOne implements OnDestroy, OnChanges {

  readonly myBehaviourSub = new BehaviorSubject<Observable<MY_CUSTOM_INTERFACE>>(NEVER);

  constructor(private readonly myService: MyService){}

  ngOnChanges(changes: SimpleChanges) {
    this.myBehaviourSub.next(
      this.myService.fetchNewValuesForAlpha()
        .pipe(
          switchMap(response => response.newValue))
        .subscribe(
          (newAlpha) => this.myService.fetchSomeData(newAlpha, beta, gamma)
          .pipe(shareReplay({refCount: true, bufferSize: 1})
         ); 
     );
   }

}

However, I encountered an error because "fetchNewValuesForAlpha" returns an observable. Despite trying to use switchMap to resolve this issue, I faced the following error message:

Argument of type 'Subscription' is not assignable to parameter of type 'Observable<MY_CUSTOM_INTERFACE>'

Answer №1

When subscribing in the ngOnChanges, a subscription is already being returned. To achieve the desired effect, consider the following code snippet. The switchMap function should be placed at the appropriate location to retrieve the fetchSomeData-data.

  ngOnChanges(changes: SimpleChanges) {
    this.myBehaviourSub.next(
      this.myService.fetchNewValuesForAlpha()
        .pipe(
          map(response => response.newValue),
          switchMap(newAlpha=>this.myService.fetchSomeData(newAlpha,beta, gamma)
           .pipe(
             shareReplay({refCount: true, bufferSize: 1})
             ) 
          )
        )
     )
  }

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 issue arises when IonViewDidLoad fails to retrieve data from the service class in Ionic after the apk file has been generated

Creating a form where users can input various information, including their country code selected from dropdowns. Upon submission, the data is displayed successfully when running in a browser. However, after building the apk file, the country codes fail to ...

Ways to prompt the debugger to pause whenever a specific script file is called during execution in Edge/Chrome debugger

I am currently in the process of debugging a Typescript web application, which is quite new to me as I have never delved into web development before. This particular project entails multiple script files and various libraries. While running the applicatio ...

How can you update the property values of a CSS class that already exists in an Angular2+ controller?

In my styles.css file, I have a CSS class called '.users' with a property of color. Now, I am looking to dynamically change the color property value of the 'users' class based on certain conditions in my controller. For instance, I want ...

In Javascript, check if an item exists by comparing it to null

I am working with a dropdown list that can be used for various types of data. Some of the data includes an isActive flag (a BOOLEAN) while others do not. When the flag is absent, I would like to display the dropdown item in black. However, if the flag exis ...

Navigating a webpage with Material select and routerLink in Angular 6

I am currently developing a feature that allows users to navigate to a page to access a list of documents from a policy. In addition, I am incorporating all policies so that users can easily move between them using a select form and direct you to the selec ...

What is the process for installing npm dependencies to a specific directory without creating a node_modules folder?

I recently published a package called main-package, which has a dependency on another package called sub-package that is already available on npm. However, when I install main-package, it creates a node_modules folder with both packages at the same level. ...

Learning to extract information from elements within components in a flexbox using Angular

Is there a way to access the element width of child components within a parent component that utilizes flex box? I am hoping to determine if the list is overflowed so I can adjust the visibility of elements accordingly. If an overflow occurs, I would like ...

How can I incorporate dynamic fields into a Typescript type/interface?

In my Typescript interface, I have a predefined set of fields like this: export interface Data { date_created: string; stamp: string; } let myData: Data; But now I need to incorporate "dynamic" fields that can be determined only at runtime. This me ...

Each styled component will yield the respective type definitions using (@types/styled-components)

Encountering a strange problem with styled-components in VSCode. Every component from styled-components is returning 'any'. https://i.sstatic.net/0kFJw.png https://i.sstatic.net/S20cS.png I had it working previously, but unsure when it stopped ...

Retrieve data from a different component in Angular 4

In my setup, I have a header component with a select search box and a stats component that displays results based on the option selected in the box. I am exploring ways to refresh the results automatically when the selection changes. One idea was to use ...

"Converting array into a string in TypeScript/Javascript, but unable to perform operations

After generating a string with the correct structure that includes an array, I am able to navigate through the JSON on sites like However, when attempting to access the array, it turns out that the array itself is null. Here is the scenario: Firstly, th ...

Bizarre Behavior of String Comparison in Typescript When Using String.toLowerCase

As someone who is naturally curious (and has no background in JS), I have decided to take the plunge into Typescript. However, I seem to have hit a roadblock. I am trying to compare two strings but want to make it easier by first converting them to lowerca ...

Traversing through an array and populating a dropdown menu in Angular

Alright, here's the scoop on my dataset: people = [ { name: "Bob", age: "27", occupation: "Painter" }, { name: "Barry", age: "35", occupation: "Shop Assistant" }, { name: "Marvin", a ...

What is the relationship between Typescript references, builds, and Docker?

I am facing a dilemma with my projectA which utilizes a common package that is also needed by my other Nodejs services. I am unsure of the best approach to package this in a Docker file. Ideally, running tsc build would compile both the project and the dep ...

What is the best way to distinguish elements in the same HTML using Angular Material?

Currently, I am working on a project using Angular material, where I have a component.html file that defines a form and a table with data. In the first image of my project, you can see the tab title, a form to add new records, and the table displaying exi ...

Is there a solution for resolving the Element Implicitness and Lack of Index Signature Error?

I encountered an issue with specialCodes[letter]. It mentions that The element implicitly has an 'any' type because the expression of type 'string' cannot be used to index type and No index signature with a parameter of type 'strin ...

"Loop through an array using forEach leads to a subscription that

I am a beginner in Angular and struggling to understand how async functions work. I have written the following code, but I am encountering an error: GET https://localhost:44353/api/ecams/id/undefined 400 and ["The value 'undefined' is not va ...

Angluar's pipe filter failing to provide unique outcomes

My application utilizes the same service data on both a Parent and Child page. While attempting to filter the data for unique values based on a specific column using ngx-filter-pipe module, I am encountering an issue where all values are still being retur ...

What is the proper place for DOM manipulation within Angular 2?

When it comes to Angular 2, the rules around DOM manipulation have evolved from Angular 1. In Angular 1, all DOM manipulation was supposed to be handled in directives for proper testability. However, with Angular 2, there seems to be a lack of clear inform ...

What is the best way to optimize reactive values using the Vue composition API?

Imagine I have a block of code like this... const computedStyle = computed(() => normalizeStyle([undefined, styleProp, undefined]) ); const computedClass = computed(() => normalizeClass([ "button", classProp, { "b ...