The Angular service "this" is altering the context of the window object

I must have made a mistake somewhere and I know I am overlooking something obvious. The aim is to create a service that provides basic authentication features such as login, logout, and checking if a user is logged in or not.

Upon loading the page, I verify a cookie and try to fetch the user from the server if the session cookie indicates that the user is already logged in. I expect minimal full page transitions, but I believe having 1-2 full pages is probably the best approach, and I prefer not to store the user data in a cookie.

I grasped that a service is built by adding data/methods to the this object. I understand that the context of 'this' changes inside promises, but I'm puzzled as to why the this context points to the window object in the isLoggedIn method?

angular.module('myNgApplication').service('MyAuthentication', function ($cookies, UserProxy) {

    this.user = null ;

    (function(){
        var SESSION_COOKIE = 'loggedIn'
        if($cookies[SESSION_COOKIE]) {
            var self = this
            UserProxy.retrieveSession().then(function(authResponse){
                console.log('init')
                console.log(self)
                self.user = authResponse
            })
        }
    }).call(this)



    this.isLoggedIn = function() {
        console.log('isLoggedIn')
        console.log(this)
        return this.user != null ;
    }

    this.login = function (email, password) {
        var self = this
        return UserProxy.login(email, password).then(function(authResponse){
            self.user = authResponse
            return self.user
        })
    }
})

Usage:

var myWelcomeController = function($scope, MyAuthentication, $timeout) {


    $scope.$watch(function(){ return MyAuthentication.user }, function() {
        console.log(MyAuthentication.user)
        $scope.user = MyAuthentication.user ;
        $timeout(MyAuthentication.isLoggedIn, 1000)
    });

};

Console:

init 
Constructor {user: null, isLoggedIn: function, login: function}

isLoggedIn 
Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}

Answer №1

$timeout is essentially an angular version of the setTimeout function in JavaScript, functioning in a similar manner.

Take a look at this example:

var foo = {
  bar: function(){
    console.log('bar this =', this);
  }
};
foo.bar(); //-> bar this = Object {bar: function}
setTimeout(foo.bar); //-> bar this = Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}

When you invoke foo.bar(), the context of the function bar is set to foo. However, when you use setTimeout(foo.bar), the setTimeout function references only the bar function and executes it with a context of Window, as noted in the documentation.

To make your code work properly, you can implement the following change:

$timeout(function(){
  MyAuthentication.isLoggedIn()
}, 1000);

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

Removing a faded out div with Vanilla JavaScript

I am struggling with a JS transition issue. My goal is to have the div automatically removed once it reaches opacity 0. However, currently I need to move my mouse out of the div area for it to be removed. This is because of a mouseleave event listener that ...

Avoid showing an image when it is outside the div container

Within a single div, I have an assortment of images that are dynamically repositioned using JQuery. $("#"+carElem).css({"left": pos.left+50 +"px"}); I am currently utilizing absolute positioning (although relative positioning yields the same outcome). Is ...

Looking to modify the contents of a shopping cart by utilizing javascript/jQuery to add or remove items?

I'm dealing with a challenge on my assignment. I've been tasked with creating a Shopping Cart using Javascript, HTML5, and JQuery. It needs to collect all the items from the shop inside an Array. While I believe I have most of it figured out, I a ...

Creating PHP functions that return a JSON string when invoked - a simple guide

I have created a script that contains various functionalities, including fetching data from a database and encoding it into JSON. However, I want to be able to call different functions to execute these scripts separately. When I attempted to define and c ...

What is the best way to insert data from a promise into MongoDB?

While attempting to integrate an array of JSON data from a different server into a MongoDB collection, I encountered the following error message: "Cannot create property '_id' on string". Even though I am passing in an array, it seems to be causi ...

Using Javascript libraries on a Chromebook: A comprehensive guide to getting started

Doing some coding on my chromebook and wondering if it's possible to download and utilize libraries such as jQuery. Would really appreciate any assistance with this! ...

How can I pass arguments from a Python command line program (compiled to an EXE) to a JavaScript file?

As I work on developing a node program, I've come across certain abilities that Python possesses which JavaScript lacks, such as utilizing Python-specific modules. To bridge this gap, I made the decision to compile Python files into EXE and then invok ...

JQGrid will automatically conceal any row that contains a false value in a given cell

I'm attempting to conceal a row if a specific cell within it contains the value false. To achieve this, I have experimented with using a formatter in the following manner: $("#list").jqGrid({ //datatype: 'clientSide', ...

Aligning dynamically-sized TextInput in React Native

I am facing a challenge in centering a text input with a width that matches the length of the input text. I have tried using alignSelf: 'center' and alignItems: 'center', but the text input is not visible without specifying a width. Fo ...

Merging text and a JSON object to retrieve the information

Having some trouble with a JSON object and retrieving values. This is the syntax that works for getting the data I need. dataJSON.companies[0].fields.Internet.length I want to dynamically evaluate the object using a string variable, like this... var me ...

Unraveling an AJAX response in JSON format using jQuery

I am a beginner in the world of Jquery and Ajax. I've crafted the code below to automatically populate a form with data after selecting an option from a combo box within a form, using guidance from this helpful post Autopopulate form based on selected ...

Having difficulty retrieving the current time of an audio element using jQuery

Currently, I am facing an issue while attempting to manage an audio element for my custom player. Despite numerous attempts, I have been unsuccessful in acquiring the currentTime and duration properties. Below is a snippet of what I've tried: var pla ...

The minification of HTML scripts may cause problems with the <script> tag

Greetings! I have a PHP script that is used to minify the page by removing any comments or spaces. Here is the script: <?php function sanitize_output($buffer) { $search = array( '/\>[^\S ]+/s', '/[^&b ...

Saving a document from an HTTP response in Angular

Can anyone help me figure out how to save a file from a server response in Angular? I want the file to be downloaded automatically once the response is received. Update: I am using a $http POST method and receiving PDF data in the response. After a succe ...

Transfer groups between divisions

In my HTML structure, I have two main divs named Group1 and Group2. Each of these group divs contains at least two inner divs, all with the class .grp_item. Currently, the grp_item class is set to display:none, except for one div in each group that has a c ...

Dependencies in Angular

After diving into Angular recently, I've been grasping the concepts well. However, one thing that still puzzles me is dependency injection. I'm unsure whether it's necessary to declare all components of my application (services, controllers ...

Does the rendered ID of an ASPX control always appear the same in the source HTML code?

Let's say I have an aspx textbox with id="txtkms". In the HTML view source, it appears as ContentPlaceHolder1_Gridview1_txtkms_1. I'm curious if this control will always be rendered as ContentPlaceHolder1_Gridview1_txtkms_1 every time I run my as ...

Disparity in response status codes during an ajax call from both client and server

Scenario: - Node/Express/Angular 1.x Issue - The client always receives a response code of 200 over the ajax call, even when the server response headers indicate 304 or 200 (confirmed in the server console and browser network response headers). What is th ...

"Learn the method for retrieving a value and adding it to an existing value in Angular

When I use autocomplete in a textbox and select an option, it is not appending down as expected. Instead, it only shows what I type in the textbox. I have tried multiple solutions but can't figure out where I am going wrong. Please review this issue: ...

"Run JavaScript code within the boundaries of the start and end of XMLHttpRequest

Currently, I am using XMLHttpRequest to execute an AJAX request without the use of jQuery, relying solely on plain old Javascript. This particular AJAX request may take some time as it calls an endpoint responsible for processing transactions. In order to ...