Launching a peek inside a modal using AngularJS through a service

Feeling a bit unsure about my approach...

I'm diving into my first AngularJS app and trying to grasp the architecture.

So, I've built a service called isAjax, utilizing the $http module to handle API calls for me.

I'm capturing the success and error responses in this service.

Here's the code - not entirely sure if the syntax is correct, but it seems to be working...

appServices.factory('isAjax', ['$http', '$q', function ($http, $q) {

    var apiController = function (url) {
        if (url.indexOf('?') > -1){
            return url.substring(url, url.indexOf('?'));
        } else {
            return url;
        }
    }

    var doHttp = function (url, method) {

    var deferred = $q.defer();

    $http({
        method: method,
        url: url
    })
    .success(function (data) {
        deferred.resolve(data);
    })
    .error(function (data, status) {

        switch (status) {

            case 404:
                bootbox.alert('api call to ' + apiController(url) + ' failed<br />URL does not exist');
                break;

            case 401:
                // Here - I would like to somehow call a directive? which would open a bootstrap modal and load a view into it.
                break;

            default:
                console.log(arguments);
                bootbox.alert('ajax error');
        }


        console.log(status);
        console.log('http errored')
    });

    return deferred.promise;
};

return {
    getData: function (url, method) {
        return doHttp(url, method);
    }
}

}]);

To use this service, I just need to inject isAjax and then call:

var dataPromise = isAjax.getData('api/globaljson', 'get');

Now, when I encounter a status code 401, I want to trigger something - possibly a directive - that will display a view in a modal.

This is where I'm hitting a roadblock... If I create a directive, how can I communicate with it from the service?

I could potentially create another service to handle it, but I know that manipulating the DOM shouldn't be done in a service.

Any guidance would be greatly appreciated.

Thanks!

Answer №1

To streamline navigation, establish a dedicated route that redirects based on specific responses. This route will load an external HTML file and connect to a controller. I recommend utilizing the angular-route-segment library for enhanced functionality within the Angular route system. For more information and examples, visit angular-route-segment.com

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

Using JavaScript to invoke a child method within a parent class

Is it recommended to call a child method from a parent class in JavaScript? In the given example in BaseComponent.js, calling this.constructHtml() is returning undefined. What could be causing this issue? Thank you! script.js import Header from './co ...

Error occurs in Typescript when attempting to store data in a record using a pointer

When working with nodes and organizing them into a tree structure, I encounter an issue: This is the definition of the interface: interface IDataObj { children: IDataObj[], frontmatter : { type: string, title: string, path: string}, name: str ...

Is bundling a Node.js backend a wise decision or a mistake?

Just a thought that crossed my mind - I understand the advantages of bundling client-side code, but what about bundling server-side code with Browserify/Webpack? Is this considered a best practice? ...

Troubleshooting Angular JS loading problems

I'm attempting to implement the Angular-Spinner in my project: Specifically, I want to use it with http.get calls. This is what I have so far: Within controllers: $scope.loading = true; $http.get('js/data/test.json').success(function(resu ...

Decoding various JSON arrays received through AJAX requests

After returning two objects as JSON through AJAX, I am facing an issue with accessing the values in these two lists. Previously, when I had only one list, I could parse it easily. data = serialize("json", vm_obj) data2 = serialize("json", user_networks_li ...

Retrieving data from the database using getStaticProps in Next.js

As I was following a tutorial on Next.js, the instructor did something that deviated from what I had learned in school and left me pondering. Here is what he did: interface FaqProps { faq: FaqModel[]; } export default function Faq({ faq }: FaqProps) { ...

Is there a different option than jQuery.ajaxSettings.traditional for use with XMLHttpRequest?

Is there a different option similar to jQuery.ajaxSettings.traditional for xmlhttprequest? or What is the method to serialize query parameters for an xmlhttprequest? ...

Display the elements of a div at a reduced size of 25% from its original dimensions

I'm currently developing a JavaScript-based iOS simulator that allows users to view their created content on an iPhone and iPad. This involves using AJAX to load the content/page into the simulator, but one issue is that the simulator isn't life- ...

Encountered an unexpected token '{' error in Discord.js and Node.js integration

let user = message.mentions.users.first(); if (message.mentions.users.size < 1) return message.reply('Please mention someone to issue ARs.').catch(console.error); mcash[${user.id}, ${message.guild.id}].mc ...

Function containing the $http.get method

I am facing an issue with my function containing multiple $http get requests. Despite needing to call another function after each request is completed, it always executes the function before the request finishes processing. What could be causing this and ...

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

Finding the element in the HTML using selenium and Python

Recently, I have been working on automated testing using Selenium. However, I have encountered a strange issue where I am unable to locate the element. Can someone please provide me with guidance on how to handle this situation? driver.find_element_by_xpa ...

Unable to locate JavaScript files within the Django project

I utilized Python 3.7 on Windows 10 to develop a Django project. settings.py: STATIC_URL = '/static/' LOGIN_URL = '/login' LOGIN_REDIRECT_URL = '/' https://i.sstatic.net/LSAdq.png I employed superuser to create some regu ...

Is there a way to update the color of a button once the correct answer is clicked? I'm specifically looking to implement this feature in PHP using CodeIgniter

Within my interface, I have multiple rows containing unique buttons. Upon clicking a button, the system verifies if it corresponds to the correct answer in that specific row. The functionality of validating the responses is already functional. However, I a ...

Tips for resolving the issue: TypeError - AppliNom.map function is not recognized

I am currently utilizing ReactJS, incorporating React.UseState and UseEffects. My challenge lies in handling a significant amount of data retrieved from a Web Service (exceeding 400 rows). To structure this data, I rely on _.groupBy from the lodash librar ...

Creating mock implementations using jest in vue applications

I have been experimenting with testing whether a method is invoked in a Vue component when a specific button is clicked. Initially, I found success using the following method: it('should call the methodName when button is triggered', () => { ...

Angular UI-Router Multiple Navigation (Horizontal Top and Vertical Left Menu)

My website has a top-level menu and left menus that are updated based on the selected top-level menu. When I click on a left menu item, it resets and becomes blank, as shown when clicking on HOME. Currently, only HOME is connected, while Route1 and Route2 ...

Detect the 'mousewheel' event on a container with a concealed overflow

Is there a way to capture the "mousewheel" event on a body with a hidden overflow? I attempted to follow the solution provided here, but unfortunately, it did not work in my situation. ...

Step-by-step guide to customizing the theme in Nuxt using Vuetify

I am new to using Nuxt and Vue, and I am attempting to switch the color theme from dark to light. The project was created using Nuxt CLI, and these are the versions I am using: "dependencies": { "core-js": "^3.8.3", "nuxt ...

Cannot retrieve authorization cookie

Currently, I am in the process of setting up backend authentication using Express, Node, and Supabase for my frontend built with React. //auth.js import { supabase } from "../config/supabaseConfig.js"; export const checkAuthorizationStatus = asy ...