"Facing a challenge with Angular 2 where an HTTP request is being triggered twice

After thorough research on Stack Overflow, I can confidently say that the issue is not with my code. However, my REST APIs are being called twice.

Here is a snippet of my code:

Component:

    export class Component  {

        constructor(private _nService: NService) {
            this.categoryList = this._nService.getCategories();
            this.getMessage();
        }

     getMessage() {
        console.log('inside getMessagecomponent');
        this._nService.getNotifications().subscribe(notifications => {
            console.log('Calling Service...');
        });

     }
    }

Service:

@Injectable()
export class NService {

    constructor(private http: Http) { }

   getNotifications() {
        console.log('inside getNotification service');      
        return this.http.get(URL)
            .map((res: Response) => res.json());
    }

}

I have added console.log statements in both the component and service to track whether the method is being called from other places or getting called twice.

Surprisingly, the console.log statements in both the component and service are only triggered once. However, the REST APIs are still being called twice.

  • I attempted to use .share() but it did not resolve the issue.
  • Unsubscribing from the call also did not work.

The sequence of the console.log outputs is as follows:

  • inside getMessagecomponent component
  • inside getNotification service
  • Calling Service...

PS: This duplication of API calls is occurring across all APIs in my project.

https://i.sstatic.net/CKgpe.jpg

Headers:

Request 1:
----------------

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, Accept, X-Requested-With, remember-me, x-dd-cust, x-dd-apitoken
Access-Control-Allow-Methods:POST, GET, PUT, OPTIONS, DELETE
Access-Control-Allow-Origin:http://localhost:8425
Access-Control-Max-Age:3600
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Type:application/json;charset=UTF-8
Date:Mon, 20 Mar 2017 07:00:40 GMT
Expires:0
Pragma:no-cache
Transfer-Encoding:chunked
X-Application-Context:application:dev:8085
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block

Response 1:
---------------

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Content-Type:application/json
Host:localhost:8085
Origin:http://localhost:8425
Referer:http://localhost:8425/dashboard
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
x-dd-apitoken:TOKEN
x-dd-cust:name

Request 2:
--------------

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, Accept, X-Requested-With, remember-me, x-dd-cust, x-dd-apitoken
Access-Control-Allow-Methods:POST, GET, PUT, OPTIONS, DELETE
Access-Control-Allow-Origin:http://localhost:8425
Access-Control-Max-Age:3600
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Type:application/json;charset=UTF-8
Date:Mon, 20 Mar 2017 07:00:40 GMT
Expires:0
Pragma:no-cache
Transfer-Encoding:chunked
X-Application-Context:application:dev:8085
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block

Response 2:
------------

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Content-Type:application/json
Host:localhost:8085
Origin:http://localhost:8425
Referer:http://localhost:8425/dashboard
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
x-dd-dd:TOKEN
x-dd-cust:name

UPDATE

Upon checking the developer console, I noticed that it is not an OPTIONS request as there are two separate GET requests visible in the network tab.

Answer №1

"The current order in which my console.log statements are appearing:

within the getMessagecomponent component

within the getNotification service

Executing Service..."

If your order matches the above, it means you are not executing 2 get requests

getNotifications will provide an observable, it will not trigger a get request. Your subscribe method will initiate a get request and if you are conducting a cross-domain request, one of your network calls will be the OPTIONS request.

Answer №2

It might be beneficial to include the sharing feature of Observable in your code.

import 'rxjs/add/operator/share';

export class Component  {

    constructor(private _nService: NService) {
        this.categoryList = this._nService.getCategories();
        this.getMessage();
    }

 getMessage() {
    console.log('inside getMessagecomponent');
    this._nService.getNotifications().subscribe(notifications => {
        console.log('Calling Service...');
    }).share();

 }
}

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

Who is in charge of initializing "background" services within Angular?

I have been studying the Angular service workers documentation (https://angular.io/guide/service-worker-communications). The examples provided demonstrate services used for managing service worker lifecycle handlers such as update and failed lifecycle. My ...

Removing items with properties that are null or undefined

My current situation involves using the AWS SDK, and I've noticed that many of its objects have members that can be undefined. Take for example S3.Object: export interface Object { /** * */ Key?: ObjectKey; /** * * ...

Getting the previous result in an observable using an interval - here's how!

Can someone help me with accessing the previous value of an observable within a Pipe observable that uses an interval? The code example is provided below: const imageStatus = interval(5000) this.statusSubscription = imageStatus.pipe( startWith(0), pair ...

Decide using Angular whether a component's value change is due to a recognized alteration

We're currently utilizing the 'switch' feature in DevExtreme and have configured the onValueChanged event to carry out a specific action. However, this event is also triggered whenever the property value of the associated object changes due ...

Node JS application facing compatibility issues with Typescript not working as intended

I've been diving into Typescript and recently followed a tutorial on how to integrate it with an express api app. However, I encountered the following error: D:\Development\Node\Ed\TypeScript\src\app.ts:5 const app: Appl ...

The TLS connection could not be established as the client network socket disconnected prematurely

While attempting to run npm install on an Angular 5 dotnetcore project that I pulled down from source tree, everything was running smoothly on my work machine. However, when I tried to do the initial npm install on my home machine, I encountered the foll ...

Ionic: Automatically empty input field upon page rendering

I have an input field on my HTML page below: <ion-input type="text" (input)="getid($event.target.value)" autofocus="true" id="get_ticket_id"></ion-input> I would like this input field to be cleared eve ...

The appearance of the Ionic segment will be altered only when the content input is clicked

Currently working on a photo editing app using ionicv2 and Adobe Creative SDK. Integration of the creative SDK has been successful. Once the CSDK returns the edited file's URL, I navigate to a new page with a segment along with the file URL. The iss ...

Activate backdrop feature in offcanvas mode

When trying to open an offcanvas panel, I discovered that adding show to its class is necessary for it to open. However, this caused the backdrop feature to stop working, and now clicking outside the panel does not close it. Is there a way to achieve the p ...

Tips to decrease the bundle size of Angular 2 with WebPack

After experimenting with various Angular 2 seed projects utilizing WebPack, I noticed that when I compile the bundle for production, the resulting file size is around 3MB. Is there a way to minimize the size of this file? An example of one of these proje ...

What is the reason for the inability of `Array<Value>, Value` to properly retrieve the type of the array value?

I am encountering an issue with the type declaration below: function eachr<Subject extends Array<Value>, Value>( subject: Subject, callback: ( this: Subject, value: Value, key: number, subject: Subject ...

What steps can I take to avoid the 404 not found error in Angular when I refresh the page?

I am facing a 404 not found error on my Angular project when I upload it to a global server and then refresh the page. How can I resolve this issue? Below is my routing.component.ts file: import { RouterModule, Routes } from '@angular/router'; i ...

Angular ngx-translate Feature Module failing to inherit translations from Parent Module

Currently, I am implementing lazy loading for a feature module. I have imported TranslateModule.forChild() with extend true to load feature-specific translations. In my app.module, I am importing TranslateModule.forRoot to load common translations. The i ...

Differences Between JavaScript and TypeScript Classes

I'm a novice when it comes to TypeScript and JavaScript classes! While learning TypeScript, I created a simple code snippet like this: class User { name: string; email: string; constructor(name: string, email: string) { this.name = name; ...

What is the best way to represent a directory structure in JSON using a C# data type?

My directory structure is as follows: v1 file1.txt file2.txt common common.txt I need to create a C# function that can traverse this directory structure and generate JSON output. The expected JSON format is like this: { "v1&qu ...

Incorporating CASL with the latest version of Angular, version

I'm currently working on implementing CASL into my Angular application, but I'm having trouble understanding how to integrate it. // Login Component ngOnInit() { var jsonBody = {}; jsonBody['email'] = 'peter@klaven'; ...

Exploring Data in Angular 2: Examining Individual Records

I am currently learning Angular and facing some challenges in structuring my questions regarding what I want to achieve, but here is my query. Within a component, I am retrieving a single user record from a service. My goal is to display this user's ...

Retrieve the value of an object without relying on hardcoded index values in TypeScript

I am working with an object structure retrieved from an API response. I need to extract various attributes from the data, which is nested within another object. Can someone assist me in achieving this in a cleaner way without relying on hardcoded indices? ...

Unable to perform the upgrade to Angular 6 due to an invalid range

I'm in the process of upgrading to Angular 6 As I follow the upgrade guide, I run into this issue: > ng update @angular/core Invalid range: ">=2.1.0" That's all the information I have. There are no additional warnings or ...

Utilizing generics within a function

Can you help me understand why I am getting an error message that says "Type 'AbstractPopup' is not assignable to type T" when using the return statement in the popupFactory(...) method? This code is just a test example for learning how generics ...