Obtaining results from several observable requests within a function

A function is currently operational, functioning by setting a value in the component when called (user.userImage).

getLoggedInUserPhoto() {
this.adalService.acquireToken('https://graph.microsoft.com')
  .subscribe(token => {
    let header = new HttpHeaders().set('Authorization', 'Bearer ' + token).set('Content-Type', 'image/jpeg');
    this.imageService.getImage('https://graph.microsoft.com/v1.0/me/photo/$value', header)
      .subscribe(blob => {
        this.imageService.getImageUrlFromBlob(blob)
          .then(res => {
            this.user.userImage = res;
          })
      })
  });
}

In attempting to replicate this functionality with a new function, I aim to have the function return a value rather than directly set it in the component. Despite searching extensively, I may be using incorrect search terms. Nevertheless, here is an attempt at achieving my desired outcome:

getPhoto(email: string): string {
return this.adalService.acquireToken('https://graph.microsoft.com')
  .subscribe(token => {
    let header = new HttpHeaders().set('Authorization', 'Bearer ' + token).set('Content-Type', 'image/jpeg');
    this.imageService.getImage('https://graph.microsoft.com/v1.0/users/'+email+'/photo/$value', header)
      .subscribe(blob => {
        this.imageService.getImageUrlFromBlob(blob)
          .then(res => {
            return res;
          })
      })
  });
}

Answer №1

If you're looking for a way to handle asynchronous requests in a more controlled manner, I recommend utilizing the switchMap operator. This operator ensures that the second request will only be triggered once the response from the first request has been received.

return this.http.get('https://graph.microsoft.com')
  .switchMap(res1 => {
    // Use res1 to further customize parameters for the second call
    this.http.get(''https://graph.microsoft.com/v1.0/users/'+email+'/photo/$value', header')
  })
  .subscribe(res2 => {
    // Process the response from the second call here
  })

Answer №2

To achieve your desired outcome, it is recommended to utilize the merge map function within the pipe. This will allow you to effectively execute your task. By using merge map, the process will wait for one subscription to finish before proceeding to the next action with the response.

return this.adalService.acquireToken('https://graph.microsoft.com').
 pipe(
     mergeMap(res => {
         this.http.get(''https://graph.microsoft.com/v1.0/users/'+email+'/photo/$value', header')
     })
 ).subscribe(res => {
  //The "res" variable contains the response from the second request
 })

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

Encountering issues with the upgrade process from Angular 12 to 14

I am looking to transition this codebase from Angular 12 to Angular 14, but I am facing issues with using ng update: https://github.com/PacktPublishing/Reactive-Patterns-with-RxJS-for-Angular/tree/main/Chapter04 Encountering the following error when runn ...

Guide to developing a universal store extension

I've been attempting to create a reactive global $store object using a plugin, but so far I have not been successful in getting it to function as intended. store.ts: import {reactive} from "vue"; export default { install: (app:any, opt ...

Tips for setting up a mdl-dialog using a declarative approach

I want to incorporate a mdl-dialog into my component following the example provided here: However, when I try to do so, the compiler throws an error stating: Can't bind to 'mdl-dialog-config' since it isn't a known property of ' ...

I encountered an issue while attempting to retrieve data using route parameters. It seems that I am unable to access the 'imagepath' property as it is undefined

Is there a way to access data when the page loads, even if it is initially undefined? I keep getting this error message: "ERROR TypeError: Cannot read properties of undefined (reading 'imagepath')". How can I resolve this issue? import { Compone ...

Issue with exporting Typescript React component

Despite searching for answers, none of the related questions have been helpful... My goal is to export React components from a TypeScript library that I plan to publish on npm. For testing purposes before publishing, I am utilizing npm link. The structu ...

Headerbar overlapping Div when scrolling

I'm currently trying to create a fixed header bar that allows the content of the page to scroll beneath it rather than displaying above it. This functionality is working on multiple pages, but I'm experiencing issues with my calendar page. When ...

What is the proper way to incorporate generics into a function in TypeScript when you plan to call it using .call()?

interface Wrapped<T> { data: T; } interface BetterWrapper<T> { betterData: T; } function abc<T>(test: Wrapped<T>): BetterWrapper<T> { return {betterData: test.data} } const result = abc<string>.apply({}, { data: ...

Utilizing Nodemailer and ReadableStreams to send email attachments stored in S3

My current challenge involves sending emails with Nodemailer that include attachments hosted in S3, utilizing JS AWS SDK v3. The example provided in the Nodemailer documentation demonstrates how to send an attachment using a read stream created from a file ...

Obtain the input value from a modal and receive an empty string if no value

Utilizing ng-multiselect-dropdown within my bootstrap modal allows users to choose multiple products. Each time an item is selected (onItemSelect), a new div is inserted using the jQuery method insertAfter(). This new div displays the quantity of the selec ...

Fetching data from MongoDB, loading over 3000 entries and implementing pagination

I'm facing a challenge where I need to display more than 3000 results in an HTML table by fetching MachineID, Username, and Data from my MongoDB. However, I am encountering difficulties when trying to render this data using datatables. The MachineID ...

The `staticAlert` property in the constructor.ts file does not have an initializer and is not explicitly assigned

import { Component, OnInit, ViewChild } from '@angular/core'; import {Subject} from 'rxjs'; import {debounceTime} from 'rxjs/operators'; import {NgbAlert} from '@ng-bootstrap/ng-bootstrap'; @Component({ selecto ...

Removing a dynamic component in Angular

Utilizing Angular dynamic components, I have successfully implemented a system to display toaster notifications through the creation of dynamic components. To achieve this, I have utilized the following: - ComponentFactoryResolve - EmbeddedViewRef - Ap ...

Is it possible to save an externally retrieved image locally using Angular?

I'm brand new to Angular and trying to work with a QR code image generated from the angularx-qrcode library. Here is the code snippet: <qrcode [qrdata]="'Your QR code data string'" [size]="256" [level]="'M'"></qrcode> ...

Spring-boot does not support the content type 'application/form-data', resulting in an HttpMediaTypeNotSupportedException

Once I had set up the configuration files application.yml, application-dev.yml, application-prod.yml in Jhipster: spring: application: name: xxx http: multipart: enabled: true max-file-size: 200MB ...

What is the best way to incorporate multiple pages and export them in an angular2 project?

Having some issues with my code. Can anyone lend a hand? import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: `page1.html` }) @Component({ selector: 'my-app2', templateUrl: `page2.html` ...

Challenge with Dependency Injection in the Handlers of NestJS CQRS repositories

As a newcomer to nodejs, I am currently delving into the implementation of NestJS's CQRS 'recipe'. In my service, I have a Request scoped with the injection of QueryBus: @Injectable({scope: Scope.REQUEST}) export class CustomerService { co ...

Encountering an Angular 13 ChunkLoadError during application deployment, despite the presence of the respective chunk

We encountered an issue with our application's upgrade from Angular 11 to 13. While running 'ng serve' on the local machine works fine, deploying it to our Azure app service causes the lazy loaded modules to fail loading. The specific error ...

mat-table dataSource is not functioning properly with REST API integration

I'm facing an issue while trying to populate a Material Table with data. My model Block has fields such as id, date, etc. The API call is made in data.service and the function getAllBlock() fetches the blocks. I tested this in the app.component.html ...

Expanding a class in Angular 2

I am attempting to enhance a method within the Angular package available at this link. import { Component, OnInit, Injectable } from '@angular/core'; import { FILE_UPLOAD_DIRECTIVES, FileUploader } from 'ng2-file-upload'; @Injectable ...

Java AWS Error: Request Entity Exceeds Size Limit

Recently I encountered an issue while trying to upload files to my S3 Bucket after deploying my Spring Boot/Angular application to Elastic Beanstalk. The error message that appeared was 413 (Request Entity Too Large). In an attempt to resolve this, I upl ...