Angular 2 declare global variable Typescript

What is the Best way to Declare and Access a Global Variable in Angular 2?

This post helps us to learn “Declare and Access a Global Variable in Angular 2” using “Typescript” and also share the steps to create and use of this global variables.

Steps –
1.     Create Global Variables.
2.     Import and Use the Global Variables in the Component.
3.     Result

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 Use 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 {
    //USERS DECLARATIONS.
    users = [];

    //HOME COMPONENT CONSTRUCTOR
    constructor(private userService: UserService, private _global: AppGlobals) { }

    //GET USERS SERVICE 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));  
    }
}
//END BEGIN – USERCOMPONENT

“user.server.ts” :-

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

//BEGIN-REGION - USERSERVICE
@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);
    }
}
//END BEGIN – USERSERVICE

Result:-




ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book