Exploring the Power of Observables in Angular 2: Leveraging the Versatility of

As a student working on developing a simple WebApp and Server, I have encountered some issues with Http.post and Http.get methods using Observables.

My main challenge is related to posting a boolean value to the server when a button is pressed. While the post process itself works fine, I noticed that every time I press the button, another subscription is added to the observable. I faced a similar issue with my http.get method but managed to resolve it using the following code snippet:

getdata() {   
if(this.subscribtion2 === null){
        this.isValid = false;
      this.subscribtion2 = this.service.get2().subscribe(

         daten => {
            this.jsonobj = daten;
            this.message = 
                [
                this.jsonobj.data.message1,
                ];
            console.log('subscribe');
            this.myModelneu = this.message[0];     
             },     
         err => this.handleError(err),
         () => console.log('Simple GET completed')
            );

    }else
   {
       this.isValid = true;
       console.log('unsubscribe');
       this.subscribtion2.unsubscribe();
       this.subscribtion2 = null;

   }
}

The get2() method is located in a different class.

  get2() {


        return Observable.interval(3000)
          .switchMap(() => this.http.get('http://127.0.0.1:3000/daten/2'))
          .map(res => res.json())

  }

Although not conventional, this approach has helped me manage the subscriptions. On the other hand, my http.post operation is as follows:

post(json: boolean) {
      console.log('post executed');
      console.log(JSON.stringify(json));

     return this.http.post('http://127.0.0.1:3000/login', { json })
     .subscribe();

   } 

I have tried going through various tutorials on Observables, but I could not find a way to post data to the server without subscribing to the Observable. Any guidance or assistance would be greatly appreciated!

Thank you for your help!

Answer №1

When making HTTP calls, such as using the methods get and post, an observable is returned which automatically completes with the result. In this case, there is no need to manually unsubscribe as the subscription will be terminated upon completion.

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

Executing the pause() function of NgbCarousel in Angular 5 when calling ngOnInit

I recently started learning Angular and using ngbootstrap for my UI development. I am facing an issue with loading the NgbCarousel in pause mode by default. Below is the code snippet that I have attempted: import { Component, OnInit, ViewChild } from ...

Why is getallheaders() not functioning properly in the mail function of PHP?

I am attempting to achieve the following: <?php // Defining function getallheaders() since it is disabled on my hosting server function getallheaders() { $headers = ''; foreach ($_SERVER as $name => $value) { if (subst ...

Testing Angular: Inability to achieve full code coverage for Ternary branch in unit testing

Currently, I am attempting to test a ternary branch that utilizes the window.location property. @Injectable() export class ABCService { private hostUrl = (window.location.host.indexOf('localhost') > -1) ? 'example.com' : window.lo ...

How to bring in an interface in Angular 2

For my Meteor app using Angular 2, I am looking to create a custom data type like the one below: interface MyCustomType { index: number; value: string; } To use this custom type across multiple files, I attempted to create a separate file named "mycu ...

What steps should I take to manage an error image that is not found in a directory on my computer?

I am currently working with a list that displays various information, along with an image search function in an img tag that looks for a specific image related to the information. However, some of the information does not have a corresponding image and I w ...

What is the proper way to invoke the correct store 'collection' using ngrx-store?

I'm currently working on a sample app to learn ngrx and I have two different sets of data - one for counters and the other for URLs. Each store is displayed correctly in their respective components, and I can also increment & decrement the counter usi ...

The error message "ngx-contextmenu - The function connectedTo() is not a valid function for this.overlay

I recently updated my angular version to 13 and also upgraded ngx-contextmenu to version 5.4.0. However, after the upgrade, I encountered an issue where the context menu was not visible and throwing an error as shown in this screenshot. To resolve the pr ...

Separate the date format string into tokens

I am currently attempting to create a function that is able to transform a date format string such as %d/%m/%Y %H:%n where the variables are always denoted by a percentage sign followed by one character, into an array of tokens: ["%d", "/", "%m", "/", " ...

difficulties arise when trying to use ngOnChanges to update an array

My code includes an array that is being updated from another component, with new Strings being added to it using the array.push() method. I have verified this update by testing it with a button, however, ngOnChanges does not seem to detect any change in ...

Adjust the width of a div in Angular 6 based on a specified condition

I need to adjust the width of a div based on certain conditions. <div [ngStyle]="'width': selectedTab =='Home' ? '50%' : '100%'"> </div> The currently selected tab is stored in "selectedTab". There ...

Downloading a JSON object in Angular 2: A step-by-step guide

How can I download a JSON object when clicking an icon in Angular 2? Below is the HTML: <i class="material-icons" (click)="download(model.model_id)">file_download</i> And here is the TypeScript code: download(mid){ let test = {"a":"b"} ...

Exploring Polymorphism in Typescript through Data Model Interfaces

Seeking out a design pattern for the following scenario: IApp.ts export interface IApp { platform: PlatformEnum; version: string; islive: boolean; title: string; iconurl: string; } IAppleApp.ts export interface IAppleApp extends IApp { ...

Saving large amounts of data in bulk to PostgreSQL using TypeORM

I am looking to perform a bulk insert/update using TypeORM The Test entity is defined below: export class Test { @PrimaryColumn('integer') id: number; @Column('varchar', { length: 255 }) testName: string; } I have the f ...

Use the bind method to wrap console.log and preserve the calling context

When it comes to logging message text while preserving the original context (class, line number), console output does the job perfectly with console.log.bind(console). However, the challenge arises when I also need to send the message to an HTTP server for ...

Firestore: Discontinue valueChanges listener (user receives "Permission Denied" message upon signing out)

Wondering if it’s possible to stop receiving updates through valueChanges() method? Whenever my users log in, I retrieve their user data using the following code: this.user$ = this.afAuth.authState.flatMap(authUser => { if (!authUser) { this.u ...

Loop through an icon in Angular 2 until a specific condition is met

Currently, I am in the process of developing my portfolio website using Angular 2 and I want to incorporate a skill matrix. For testing purposes, I am using a square provided by font-awesome as an example. <tbody *ngFor="let skill of skills"> <tr ...

Transform array of elements from type T1 to element in the array to type T2

Here is a Typescript class I am working with: export class Envelope<T> { result: T; constructor(result: T) { this.result = result; } } I'm trying to convert Envelope<RecentPostResponse[]> to Observable<PostModel[]>: getP ...

Executing a series of API calls using Rxjs in Angular that result in a null response

I encountered a situation where I needed to make sequential API calls using RxJs in Angular. However, despite successfully implementing the calls, I am struggling with a null error. In this scenario, the second API call depends on receiving an id from the ...

Cypress encounters a SyntaxError while running in continuous integration due to an unexpected token 'export' with the cypress-io/github-action@v2 typescript

Within my cypress plugin file located at frontend/cypress/plugins/index.ts, I have the following code snippet: export default ((on, config) => { // `on` is used to hook into various events Cypress emits // `config` is the resolved Cypress config }) ...

Facing an issue with AngularJS where I am able to retrieve data.data, but struggling to assign it to a scope variable

Currently, I am developing a website using AngularJS that retrieves questions and multiple-choice answers from an Amazon Web Services table. This data is used to dynamically create a prelab questions page. The http get request is functioning properly; when ...