What is the process for combining two services into a single, unified service?

In my Angular 8 application, I have a service structured like this:

export class ProfileUserService {
  user$ = this.authService.loginStatus().pipe(take(1));

  constructor(private profileService: ProfileService, private authService: AuthService) {}

  getProfile(): Observable<ProfileApi> {
    return this.user$.pipe(mergeMap(({ profile }) => this.profileService.get(profile.participant)));
  }
}

Within a component called SettingsAccountComponent, I utilize this service by calling the method as shown below:

export class SettingsAccountComponent extends FormCanDeactivate implements OnInit, OnDestroy {

 constructor(
    private profileUserService: ProfileUserService){}

 ngOnInit() {
    this.innerWidth = window.innerWidth;
    this.profileSubscription = this.profileUserService.getProfile().subscribe((profile: ProfileApi) => {
      this.profile = profile;
      this.deletePicture = false;
      this.buildForm();
    });
  }




}

However, I would like to directly call the ProfileService within the SettingsAccountComponent component like this:

private profileService: ProfileService

The issue arises with the following line of code:

 user$ = this.authService.loginStatus().pipe(take(1));

As I require this for retrieving the participantId. Therefore, my question is: How can I integrate the ProfileService, specifically this section:

 this.profileSubscription = this.profileService.get().subscribe((profile: ProfileApi) => {
      this.profile = profile;
      this.deletePicture = false;
      this.buildForm();
    });

With the following code snippet:

 user$ = this.authService.loginStatus().pipe(take(1));

since the get() method currently expects a ParticipantId?

What changes do I need to make to address this issue?

Thank you

Answer №1

If you're looking for a solution, consider using a switchMap.

Give this a try:

import { switchMap } from 'rxjs/operators';
...
this.profileSubscription = this.profileService.user$.pipe(
  switchMap(({ profile }) => this.profileService.get(profile.participant))
).subscribe((profile: profileAPI) => {
  this.profile = profile;
  this.deletePicture = false;
  this.buildForm();
});

It looks like you're already using mergeMap in your service, and switchMap functions similarly.

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

What is the method to remove the overlay from view?

Can anyone help with a small issue I'm having? When I click on button one, a modal popup appears but the overlay doesn't disappear when unloading. I've tried the code below, but can someone suggest what might be causing the problem? var po ...

How to use Angularjs to designate an active item in a select list

Check out this list I have: https://i.sstatic.net/NPZ1V.png It is generated by this code snippet: <select multiple size=11 ng-model="AvailableColumns" ng-show="NamesAvailable" ng-options="item for item in names"> ...

Using TypeScript to Add Items to a Sorted Set in Redis

When attempting to insert a value into a sorted set in Redis using TypeScript with code like client.ZADD('test', 10, 'test'), an error is thrown Error: Argument of type '["test", 10, "test"]' is not assigna ...

Difficulty encountered while AngularJS is integrating ASP.NET PartialView

I am facing an issue with processing HTML obtained from a PartialView Ajax call in AngularJS. The complication arises from the fact that some JavaScript code is updating the element.html property after the page has loaded. Unfortunately, I am unable to mod ...

The HTML page is failing to call the function in the JavaScript application

I recently started taking a YouTube Javascript course on chapter 34 titled "Make start button work" Javascript tutorial My HTML, CSS, and Javascript files are all located in the same folder. I am using VS Code along with the Live Server extension for codi ...

Exploring AngularJS: When to Choose Directives Over Controller-specific Code in Unique Situations

Currently, I am faced with a practical case that I consider to be theoretical. The task at hand involves working on a single page application (SPA) with multiple partials (currently 3) and a dynamic menu that transitions through various states to create a ...

What is the best way to update image CSS following a rotation using JavaScript?

Discover a neat CSS trick for always centering an image in a div, regardless of its size or aspect ratio. <style> .img_wrap { padding-bottom: 56.25%; width: 100%; position: relative; overflow: hidden; } #imgpreview { display: bl ...

Incorporate my personalized icons into the button design of ionic 2 actionSheet

I'm struggling to figure out how to incorporate my personal icon into the actionSheet feature of ionic 2/3. presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Mode', buttons: [ { ...

Expiration Date of Third-Party Cookies

I need help retrieving the expiration date of a third-party cookie programmatically using JavaScript. Even though I can see the expiry time in the browser's DevTools (refer to the screenshot at https://i.sstatic.net/BW072.png), I am struggling to figu ...

Looking to utilize JavaScript or jQuery to call a web service without the need for any C# code

I need to access an asp.net web service using only JavaScript or jQuery without any C# code. I have created a simple web service as shown below: [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] ...

Convert HTML templates into JavaScript on the client side using Angular framework along with Browserify, Babel, ES2015, and Gulp

Having trouble with my Browserify Angular configuration file, specifically when using require() to load HTML templates. I attempted to use stringify or browserify-ng-html2js in the transform() function, but it resulted in multiple transform calls in my gul ...

The Bootstrap Navbar appears hidden beneath other elements on mobile devices

While using bootstrap to style my header contents, I encountered a strange issue. The navbar that appears after clicking on the hamburger menu is displaying behind all the components. Even though I've set the z-index to the maximum value, it still doe ...

Error: The function gethostname has not been declared

I attempted to set a variable using gethostname() (1) and with $_SERVER(2), but I always receive an error message saying ReferenceError: gethostname is not defined. My goal is simply to fetch the current system name into a variable using JavaScript within ...

I encountered a difficulty trying to assign a value to @Input decorators in the spec file

While writing a test case for form submission, I encountered an issue where the Input decorator (e.g. station) value is reassigned during form submission. However, when attempting to define this Input value in the spec file, the component.station value is ...

When using Vue3 along with Axios.post, the data is being serialized incorrectly

Goal: I need to send the data {"username": myuser, "password": mypswd} to an API endpoint in order to receive a token for further communication with the API. The following code snippets attempt to achieve this: // Attempt # 1 let re ...

Filter out all elements that come before the comma in the sorted array's output

Looking for a solution to modify my code so the output is just "Bothell" without the comma and count part. let As = document.getElementsByTagName('a'); let towns = new Map(); for(let a of As) { let town = a.textContent.split(',') ...

Using console.log() within a method while chaining in JavaScript/jQuery

I've been experimenting with developing jQuery plugins and I'm interested in chaining methods. The jQuery tutorial (found here: https://learn.jquery.com/plugins/basic-plugin-creation/) mentions that you can chain methods by adding return this; at ...

In jQuery selectors, providing two variables may not yield any results, yet inputting the same string manually produces the desired output

For instance: let a = "1234"; let b = "line1\\\\.5"; Now, this particular code line: "#" + a + b; Produces the following string "#1234line1\\.5" And when I use it in the select ...

Retrieving two sets of AJAX data at the same time

Recently, I've encountered a challenge with filling in data from a MySQL server via PHP into two tables in my HTML. As someone new to website development, I might not be articulating the issue correctly. In my HTML, I've included my external .js ...

Tips for setting an identification value within mongodb?

Currently, my focus is on utilizing node.js and mongoose. I am in the process of developing a REST API to showcase my User model: var userSchema = new Schema({ _id: {type:Number}, username: {type:String}, age: {type:Number}, genre:{type: Number,ref:&a ...