加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 使用可注入服务来设置APP_BASE_HREF的配置

发布时间:2020-12-17 07:01:37 所属栏目:安全 来源:网络整理
导读:我正在编写一个带有typescript 2.0.3的角度2.1.0项目. 我使用以下代码创建了app-config服务: import { Injectable } from '@angular/core';@Injectable()export class AppConfigService { public config: any = { auth0ApiKey: 'API_KEY',auth0Domain: 'DOM
我正在编写一个带有typescript 2.0.3的角度2.1.0项目.

我使用以下代码创建了app-config服务:

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

@Injectable()
export class AppConfigService {
  public config: any = {
    auth0ApiKey: '<API_KEY>',auth0Domain: '<DOMAIN>',auth0CallbackUrl: '<CALLBACK_URL>',appBaseHref: '/'
  }

  constructor() {}

  /* Allows you to update any of the values dynamically */
  set(k: string,v: any): void {
    this.config[k] = v;
  }

  /* Returns the entire config object or just one value if key is provided */
  get(k: string): any {
    return k ? this.config[k] : this.config;
  }
}

现在我想在app-module.ts上使用该可注入服务来设置APP_BASE_HREF提供程序.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { AppComponent } from './app/app.component';
import { HelpComponent } from './help/help.component';
import { WelcomeComponent } from './welcome/welcome.component';
import {APP_BASE_HREF} from "@angular/common";
import { MaterialModule } from "@angular/material";
import { AUTH_PROVIDERS }      from "angular2-jwt";
import { RouterModule }  from "@angular/router";
import {AppConfigService} from "app-config.service";

const appConfigService = new AppConfigService();    

@NgModule({
  declarations: [
    AppComponent,HelpComponent,WelcomeComponent
  ],imports: [
    BrowserModule,FormsModule,HttpModule,MaterialModule.forRoot(),RouterModule.forRoot([
      { path: "",redirectTo:"welcome",pathMatch:"full"},{ path: "welcome",component: WelcomeComponent },{ path: "help",component: HelpComponent},{ path: "**",redirectTo:"welcome"}
    ])
  ],providers: [AUTH_PROVIDERS,{provide: APP_BASE_HREF,useValue:appConfigService.get('appBaseHref')}],bootstrap: [AppComponent]
})
export class AppModule {
}

所以在这里我将类启动到const并使用它.有没有一种方式注入凉爽和性感的方式?

例如,对于我的auth服务,我在构造函数中定义了它

constructor(@Inject(AppConfigService) appConfigService:AppConfigService)

还有办法在这里做一件性感的事吗?或者只是按原样离开?

谢谢

解决方法

您可以将工厂用于APP_BASE_REF

providers: [
  AppConfigService,{
    provide: APP_BASE_HREF,useFactory: (config: AppConfigService) => {
      return config.get('appBaseHref')
    },deps: [ AppConfigService ]
  }
]

将AppConfigService添加到提供程序后,可以将其注入工厂和身份验证服务.这通常是应该如何完成的.稍后如果说AppConfigService可能需要一些依赖,它将通过注入系统处理.

也可以看看:

> What is the difference between @Inject vs constructor injection as normal parameter in Angular 2?关于你对@Inject的使用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读