What is the procedure for defining a global variable in AngularJs 2?

As I work on developing a shopping cart application, I am faced with the task of declaring a global variable. I also need to change this variable from various components within the application.

Answer №1

Steps to Create and Use Global Variables in Angular:

  1. Create Global Variables.
  2. Import and Utilize the Global Variables in the Component.
  3. Result

To Create Global Variables: "app.global.ts"

import { Injectable } from '@angular/core';

@Injectable()
export class AppGlobals {
    readonly baseAppUrl: string = 'http://localhost:57431/';
    readonly baseAPIUrl: string = 'https://api.github.com/';
}

Import and Utilize the Global Variables in the Component: "user.component.ts"

import { Component, Injectable} from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule, Http } from '@angular/http';
import { UserService } from '../service/user.service';
import { AppGlobals } from '../shared/app.globals';


@Component({
    selector: 'user',
    templateUrl: './user.component.html',
    styleUrls: ['./user.component.css'],
    providers: [UserService, AppGlobals]
})

export class UserComponent {
    // Declare Users
    users = [];

    // Constructor
    constructor(private userService: UserService, private _global: AppGlobals) { }

    // Fetch Users on Page Load
    ngOnInit() {
        this.userService.getAPIUsers(this._global.baseAPIUrl + 'users/hadley/orgs').subscribe(data => this.users = data);
        this.userService.getAppUsers(this._global.baseAppUrl + 'api/User/GetUsers').subscribe(data => console.log(data));  
    }
}

"user.server.ts":

import { Injectable, InjectionToken } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class UserService {
    constructor(private _http: Http) {
    }

    getAPIUsers(apiUrl) {
        return this._http.get(apiUrl).map((data: Response) => data.json());
    }

    getAppUsers(apiUrl) {
        return this._http.get(apiUrl).map((data: Response) => data);
    }
}

Reference Link

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

Creating a Typescript HttpInterceptor and ensuring its compatibility with minification techniques

Currently, I am trying to implement an Angular HttpInterceptor based on the solution provided in this Stack Overflow response: However, I am struggling with the factory method: public static Factory($q: ng.IQService) { return new AuthenticationInter ...

Is there a feature in Stepper that allows for event handling when steps are changed?

For my project, I am utilizing the mat-stepper component along with a mat-Datatable inside it. In each step of the stepper, I need to dynamically hide and show different columns based on some data. Is there a way to send this data to trigger changes at eve ...

Could Typescript decorators be used as mixins?

In the process of developing a complex Angular2 application, I have created a base class that serves as the foundation for my components: export abstract class ReactiveComponent implements OnInit, OnDestroy, AfterViewInit { abstract ngOnInit(): void; ...

Tips for verifying the presence of a value within an array using checkboxes

My firestore database contains a collection named world with a sub-collection called languages I have developed two functions: one to retrieve all documents from the sub-collection languages, and another function to fetch every language if the userUid val ...

Guide to implementing basic authentication within an HTTP request in Angular 4

I'm new to this and I only have experience with the http post method. I need to send the username and password as base authentication for every API request. onSubmit = function(userdata){ this.tokenkey = localStorage.getItem('logintoken&apos ...

Ensure that typescript examines the context of 'this' within unrestricted functions

I'm having trouble getting Typescript to detect an error in the code snippet below: function foo() { console.log(this.x.y) } foo() When I run it using npx ts-node a.ts, there are no Typescript errors displayed, but it naturally fails with TypeEr ...

Using Firebase: retrieving getAdditionalUserInfo in onCreate of a Firebase Cloud function

Can anyone help me figure out how to retrieve extra data from a SAML login provider in the backend (firebase functions)? I can see the data on the client side but I'm struggling to access it in the backend. I've specified these dependencies for ...

Showing information in a modal dialog in an Angular 4 application

As an Angular 4 developer, I am working on an application where I need to display data in a dialog. To achieve this, I am using @Output to pass data from the child component to the parent component. In the parent component, my code looks like this: expor ...

Ways to receive real-time notifications upon any modifications in my cloud firestore database?

I am currently in the process of developing a chat application using Angular and Firebase Cloud Firestore. My goal is to have a counter on the client side that updates whenever any document in the 'groups' collection is updated. Within my clien ...

Issue with mediaelement in Angular 8: video playback does not display after 2 seconds

I'm encountering an issue with MediaElement js when trying to play videos in .m3u8 format within a slider containing multiple videos. Whenever I click on the play button for any video, only a 2-second clip is shown before the video disappears. Any as ...

Unable to submit data to PHP script using Angular 2

I am currently attempting to send a post request to a PHP script that contains the necessary data I require. Within home.component.ts: import { Component, OnInit } from '@angular/core'; import { UserComment } from '../definition/us ...

Exploring the best practices for utilizing the error prop and CSS with the Input API in Material UI while utilizing context

When working with the MUI Input API props and CSS, I encountered an issue related to the {error} and its use. This is how my code looks: const [value, setValue] = useState<string>(cell.value); const [startAdornment, setStartAdornment] = useState< ...

Deciding the conditional type within an IDE while using an If statement

When dealing with a type that can have two formats based on the value of one of its keys, such as: type singleOrMultiValue = {isSingle: true, value: string} | {isSingle: false, set: Array<string>} I have found it useful in preventing errors like con ...

Guide to implementing an enum in an Angular Component

Having a global state (or "mode") in my Angular Components is leading me to look for more efficient ways to code. Here is what I have tried: @Component({ .... }) export class AbcComponent implements OnInit { enum State { init, view, edit, cre ...

How can I specify a "router" member variable in Angular?

In Angular 9, I am working on a parent component where I need to pass a function to a child component. Specifically, I want to pass the "onNavigate" function to the child component... import { Router, ActivatedRoute } from '@angular/router'; ... ...

Using Cypress and JWT, automate the login process for JHipster

Is there a way to automate the bypassing of the JHipster login screen? This is my goal: let jwt_token before(function fetchUser() { cy.request('POST', '/api/authenticate', { username: 'user', password: &a ...

Why is there a discrepancy between the value displayed in a console.log on keydown and the value assigned to an object?

As I type into a text box and log the keydown event in Chrome, I notice that it has various properties (specifically, I'm interested in accessing KeyboardEvent.code). Console Log Output { altKey: false bubbles: true cancelBubble: false cancelable: t ...

iterating over a nested map within a map in an Angular application

I wrote a Java service that returns an observable map<k, map<k,v>> and I'm currently struggling to iterate through the outer map using foreach loop. [...] .then( (response: Package) => { response.activityMap.forEach((key: s ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...