angular4-创建一个全局变量,该变量也可以在视图中访问 [英] angular4 - create a global variable that can be also accessed in views

查看:218
本文介绍了angular4-创建一个全局变量,该变量也可以在视图中访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个既可以从组件又可以从视图访问的全局变量?

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

此刻,我创建了一个global.ts文件,如下所示:

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';

然后,我可以在这些组件中使用"GlobalVariable.BASE_API_URL".我不喜欢它有两个问题.首先,我必须在每个单个组件中导入的部分,是否可以一次对所有组件进行导入?但是实际上那是我可以忍受的一个问题.更大的问题是,我似乎可以在html文件中访问该变量.有解决方案吗?

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.

服务:

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

@Injectable() 
export class DataService {
  serviceData: string; 
}

组件/模板:

import { Component } from '@angular/core'
import { DataService } from './data.service';

@Component({ 
 template: ` 
  <div> 
    <h2>Data: {{ dataService.serviceData }} </h2> 
  </div> 
  `
})


export class A {

  constructor(public dataService: DataService) {
     console.log(dataService.serviceData);
  } 
}

但是请注意,您要做需要使用imports语句导入服务,并在需要该服务的每个组件中使用构造函数注入服务.

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.

这篇关于angular4-创建一个全局变量,该变量也可以在视图中访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆