App.settings - Angular方式? [英] App.settings - the Angular way?
问题描述
我想在我的App中添加一个 App Settings
部分,其中包含一些consts和预定义值。
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.
问题:
如何使用app.settings值Angular方式?
How can I consume "app.settings" values the Angular way?
NB当然我可以创建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 $中的环境文件c $ c>对于静态
应用程序范围设置
就像API端点一样,但根据项目的要求,您最有可能最终同时使用两者,因为环境文件只是对象文字,而使用 InjectionToken
的可注入配置可以使用环境变量ables,因为它是一个类,可以根据应用程序中的其他因素应用逻辑来配置它,例如初始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 { }
现在您可以将其转换为任何组件,服务等:
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键入check config。
You can then also type check the config using the exported AppConfig.
这篇关于App.settings - Angular方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!