简体   繁体   English

我如何在AngularJs 2中声明一个全局变量

[英]How I can declare a global variable in AngularJs 2

我正在创建一个购物车,我需要声明一个全局变量,并希望从不同的组件中更改变量。

Steps – 脚步 -

  1. Create Global Variables. 创建全局变量。
  2. Import and Use the Global Variables in the Component. 导入并使用组件中的全局变量。
  3. Result 结果

Create Global Variables :- “app.global.ts” 创建全局变量:-“ 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” 导入和使用组件中的全局变量: - “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” :- “ 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`enter code here`

Ref Link 参考链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM