App.settings - Angular 的方式? [英] App.settings - the Angular way?
问题描述
我想在我的应用程序中添加一个 App Settings
部分,其中将包含一些常量和预定义的值.
I want to add an App Settings
section into my App where It will contain some consts and pre defined values.
我已经阅读了使用 OpaqueToken
这个答案> 但它在 Angular 中已被弃用.此文章 解释了差异,但没有提供完整的例子,我的尝试没有成功.
I've already read this answer which uses OpaqueToken
But it is deprecated in Angular. This article explains the differences but it didn't provide a full example , and my attempts were unsuccessful.
这是我尝试过的(我不知道它是否正确):
Here is what I've tried ( I don't know if it's the right way) :
//ServiceAppSettings.ts
import {InjectionToken, OpaqueToken} from "@angular/core";
const CONFIG = {
apiUrl: 'http://my.api.com',
theme: 'suicid-squad',
title: 'My awesome app'
};
const FEATURE_ENABLED = true;
const API_URL = new InjectionToken<string>('apiUrl');
这是我想使用这些常量的组件:
And this is the component where I want to use those consts :
//MainPage.ts
import {...} from '@angular/core'
import {ServiceTest} from "./ServiceTest"
@Component({
selector: 'my-app',
template: `
<span>Hi</span>
` , providers: [
{
provide: ServiceTest,
useFactory: ( apiUrl) => {
// create data service
},
deps: [
new Inject(API_URL)
]
}
]
})
export class MainPage {
}
但它不起作用并且我收到错误消息.
But it doesn't work and I get errors.
问题:
如何以 Angular 的方式使用app.settings"值?
How can I consume "app.settings" values the Angular way?
注意我当然可以创建 Injectable 服务并将其放在 NgModule 的提供者中,但正如我所说,我想使用 InjectionToken
来实现,Angular 方式.
NB Sure I can create Injectable service and put it in the provider of the NgModule , But as I said I want to do it with InjectionToken
, the Angular way.
推荐答案
我想出了如何用 InjectionTokens 做到这一点(见下面的例子),如果你的项目是使用 Angular CLI
构建的,你可以将 /environments
中的环境文件用于静态 应用程序范围设置
,例如 API 端点,但根据您项目的要求,您很可能最终会同时使用这两种环境文件只是对象文字,而使用 InjectionToken
的可注入配置可以使用环境变量,并且由于它是一个类,因此可以根据应用程序中的其他因素(例如初始 http 请求)应用逻辑来配置它数据、子域等
I figured out how to do this with InjectionTokens (see example below), and if your project was built using the Angular CLI
you can use the environment files found in /environments
for static application wide settings
like an API endpoint, but depending on your project's requirements you will most likely end up using both since environment files are just object literals, while an injectable configuration using InjectionToken
's can use the environment variables and since it's a class can have logic applied to configure it based on other factors in the application, such as initial http request data, subdomain, etc.
注入令牌示例
/app/app-config.module.ts
import { NgModule, InjectionToken } from '@angular/core';
import { environment } from '../environments/environment';
export let APP_CONFIG = new InjectionToken<AppConfig>('app.config');
export class AppConfig {
apiEndpoint: string;
}
export const APP_DI_CONFIG: AppConfig = {
apiEndpoint: environment.apiEndpoint
};
@NgModule({
providers: [{
provide: APP_CONFIG,
useValue: APP_DI_CONFIG
}]
})
export class AppConfigModule { }
/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppConfigModule } from './app-config.module';
@NgModule({
declarations: [
// ...
],
imports: [
// ...
AppConfigModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
现在你可以直接将其 DI 到任何组件、服务等中:
Now you can just DI it into any component, service, etc:
/app/core/auth.service.ts
import { Injectable, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { APP_CONFIG, AppConfig } from '../app-config.module';
import { AuthHttp } from 'angular2-jwt';
@Injectable()
export class AuthService {
constructor(
private http: Http,
private router: Router,
private authHttp: AuthHttp,
@Inject(APP_CONFIG) private config: AppConfig
) { }
/**
* Logs a user into the application.
* @param payload
*/
public login(payload: { username: string, password: string }) {
return this.http
.post(`${this.config.apiEndpoint}/login`, payload)
.map((response: Response) => {
const token = response.json().token;
sessionStorage.setItem('token', token); // TODO: can this be done else where? interceptor
return this.handleResponse(response); // TODO: unset token shouldn't return the token to login
})
.catch(this.handleError);
}
// ...
}
然后,您还可以使用导出的 AppConfig 键入检查配置.
You can then also type check the config using the exported AppConfig.
这篇关于App.settings - Angular 的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!