Ensure to add the callback function to the observable before initiating the subscription

I'm struggling with using the Rxjs library, particularly when working with Observables:

In my Angular 2 application, I make API calls using the HTTP library which returns Observables.

The issue arises when I need to update a user:

function updateUser(user: User) {
    return this.http.put("http://myAPI/user/update", user)
}

What I want is to automatically update the user every time the "updateUser" function is called, without having to do it manually in the calling side like this:

function updateUser(user: User) {
    return this.http.put("http://myAPI/user/update", user).addCallback( updatedUser => {
        this.user = updatedUser.json()
    })
}

In simple terms, I am looking for a way to have a function executed every time "updateUser()" is subscribed. Is there a solution for this?

Thank you for your assistance!

Answer №1

To clarify, it seems like you are looking to alter the output of your observable in order to consistently return the user.

If so, you can achieve this by utilizing the Observable.map method

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-map

For your specific scenario, the code could resemble something along these lines

function updateUser(user: User) {
    return this.http.put("http://myAPI/user/update", user)
        .map(response => {
            return response.json();
        });
}

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

Is there a way to determine if a tuple is of infinite or finite length?

Is there a way to determine if a tuple is finite or infinite? I've been working on a solution, but it doesn't cover all cases: type IsFinite<T extends any[], Finite = true, Infinite = false> = T extends [] ? Finite : T extends (infer E ...

Issue: The DynamicTestModule is unable to provide a RouterLinkWithHref due to a NullInjectorError indicating that there is no provider for Router

As I prepare the unit test case for the AppComponent, which has a router as an injected dependency and includes RouterTestingModule in my TestBed setup, I am encountering a strange error. Below is the error log: Error: StaticInjectorError(DynamicTestModul ...

What is the most effective way to receive all values sent to an Observer upon a new subscription?

I have an observer that receives various values emitted to it at different times. For instance sub = new Subject<any>(); sub.next(1); sub.next(2); sub.next(3); #hack 1 sub.next(4); sub.next(5); sub.next(6); #hack 2 If there is a ...

Utilizing Angular http.post to retrieve data from Cloud Function via POST request

Trying to send a POST request to a Google Cloud Function from Angular using @angular/common/http. The documentation for Angular http v7 lacks comprehensive examples, with no information on how to include data or objects in the request. Angular code snippe ...

An issue with the animation script in Ionic

I'm having trouble converting this to an Ionic application. Here's my code sample. Can anyone help me with putting this code correctly in Ionic? I'm trying to achieve something like this example <script src="https://cdnjs.cloudflare.com ...

Retrieve the content text while handling errors using RxJs

When my Node.js server encounters an error with status 401, it sends out a message: https://i.stack.imgur.com/bOOF3.png https://i.stack.imgur.com/Kcv27.png The code responsible for this is as follows: res.status(401).send('Invalid user or password & ...

When executing prisma generate, an error of TypeError is thrown stating that the collection is

While using typescript with Prisma, I encountered an issue when trying to run prisma generate, as it kept throwing the following error: TypeError: collection is not iterable. at keyBy (/node_modules/@prisma/client/generator-build/index.js:57685:21) at ...

I'm seeking clarity on the proper replacement for ngModel within this Angular code, as I've been cautioned about using form control name and ngModel simultaneously

I have been using ngModel and formControlName together, which is causing a warning to appear in the console. I am trying to resolve this issue by removing ngModel, but I'm unsure of what to replace it with. I've attempted a few solutions, but non ...

Selecting multiple items using PrimeNG's AutoComplete with preselected values

https://i.sstatic.net/Yju8E.png Is there a method for displaying preselected values in PrimeNg AutoComplete Multiple mode? I attempted to include <p-autoComplete value="myValue"></p-autoComplete>, but it had no effect. ...

Retrieve the outermost shell of the VUEjs wrapper test-utils

While working on a VueJS test, I encountered an issue where accessing the outermost layer of HTML seemed impossible. No matter what methods I tried, the outermost layer was always ignored. Is there a way to gain access to this outermost layer so that I c ...

Angular fails to establish connection due to termination before receiving a handshake response

While attempting a socket connection, an error popped up. I am following this tutorial on tutorialedge.net but using a different endpoint for implementation. socket.service.ts import { Injectable } from '@angular/core'; import * as Rx from & ...

How do you verify an OpenID Connect access token produced by Azure AD v2 in an ASP.NET Core web API?

What is the best way to verify an OpenID Connect Access Token generated by Azure AD (v2) in ASP.NET Core Web API? Here's the situation: I have an Angular 8 Client Application that receives an OpenID Connect access Token post Login. The Client can us ...

Issue with PrimeNG Carousel width on mobile devices

Currently, I am in the process of developing a system interface with Angular and PrimeNG specifically for mobile devices. The main requirement is to have a carousel to display a set of cards. After evaluating different options, I decided to utilize the ngP ...

Typescript PDFjs encountering loading issues with corrupt files

In my Vue.js application, I have the following TypeScript class: /** Taken from https://github.com/VadimDez/ng2-pdf-viewer/blob/master/src/app/pdf-viewer/pdf-viewer.component.ts */ import { Component, Vue } from 'vue-property-decorator'; import ...

When using Angular's `createComponent()` method, an error may be thrown with the message "ERROR TypeError: Cannot add

I am currently working on a project where I am dynamically creating components. The component's class is being passed via an ngrx action and the process involves: loadComponent(componentType: Type<any>): void { const viewContainerRef = this.co ...

Comparison between TypeScript's variable scope and JavaScript's variable scope

While researching, I discovered some intriguing discrepancies between the documentation regarding a commonly asked question. The TypeScript docs suggest that variables declared with var will escape the containing function's scope, but according to MS ...

At what point are routed components initialized?

Here is a route setup I am working with: path: ':id', component: ViewBookPageComponent }, After adding this route, an error keeps popping up: Error: Cannot read property 'id' of null I haven't included a null check in the compo ...

Tips for transforming Http into HttpClient in Angular 5 (or higher than 4.3)

I have successfully implemented code using Http and now I am looking to upgrade it to use the latest HttpClient. So far, I have taken the following steps: In App.module.ts: imported { HttpClientModule } from "@angular/common/http"; Added HttpClientModul ...

Are Angular 2 animations and transitions exclusively compatible with Chrome browsers?

I've recently developed a web application using Angular2 and wanted to test its cross-browser compatibility. However, I noticed that the cool animations are only working in Chrome. Below is an excerpt from one of my components: @Component({ selec ...

Differences between making HTTP post requests in Ionic 1 with AngularJS and Ionic 3 with Angular

After working extensively with Ionic 1 AngularJS, I encountered some problems with simple HTTP post requests when transitioning to the new trend of Ionic 3 Angular. Let me provide some context for the scenario. app.module.ts import { HttpModule} from &a ...