angular4设置全局变量,angular4-创建一个全局变量,该变量也可以在视图中访问

Is it possible to create a global variable that can be accessed from both components and views?

At the moment i created a global.ts file like this:

export const GlobalVariable = Object.freeze({

BASE_API_URL: 'http://www.asdf.com/'

});

And then i have to import it in every component:

import { GlobalVariable } from '../shared/global';

Then i can use "GlobalVariable.BASE_API_URL" in those components. There are two problems with it i dont like. First the part that i have to import it in every single component, is it possible to do a import for all components once? But actually thats a problem i can live with. The bigger problem is that i can seem to access that variable in my html files. Is there a solution for this?

解决方案

You can to some extent, yes. You can create a service, define a property in that service, and then you can access that property from any component or any template ... as long as the service is injected into the component.

Service:

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

@Injectable()

export class DataService {

serviceData: string;

}

Component/template:

import { Component } from '@angular/core'

import { DataService } from './data.service';

@Component({

template: `

Data: {{ dataService.serviceData }}

`

})

export class A {

constructor(public dataService: DataService) {

console.log(dataService.serviceData);

}

}

But notice that you do need to import the service with the imports statement and inject the service using the constructor in every component that needs it.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值