1
我正在創建一個購物車,我需要聲明一個全局變量並且想要從不同的組件中更改變量。我如何在AngularJs中聲明一個全局變量2
我正在創建一個購物車,我需要聲明一個全局變量並且想要從不同的組件中更改變量。我如何在AngularJs中聲明一個全局變量2
步驟 -
創建全局變量: - 「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/';
}
進口和使用全局變量的組件: - 「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`
的可能的複製[2角 - 最新最好的方式來存儲,如身份驗證的全局變量令牌因此所有的類都對它們的訪問(http://stackoverflow.com/questions/33598153/angular-2 -whats最最好的方式到店全局變量樣認證TOK) –