2016-03-24 32 views
1

私はショッピングカートを作成しています。グローバル変数を宣言し、別のコンポーネントから変数を変更する必要があります。AngularJsでグローバル変数を宣言する方法2

+1

[Angular 2 - 認証トークンのようなグローバル変数を格納する最良の方法は、すべてのクラスがそれらにアクセスできるようにするのですか?](http://stackoverflow.com/questions/33598153/angular-2グローバル変数に似た認証トークン) –

答えて

0

ステップ -

  1. グローバル変数を作成します。
  2. コンポーネント内のグローバル変数をインポートして使用する。結果

  • は、グローバル変数を作成します -

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

    インポート「app.global.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」: -

    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

  • 関連する問題