Skip to content

Instantly share code, notes, and snippets.

@touhidrahman
Last active March 22, 2022 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save touhidrahman/b76adfd71fc26cb7d9f770f3b69516e0 to your computer and use it in GitHub Desktop.
Save touhidrahman/b76adfd71fc26cb7d9f770f3b69516e0 to your computer and use it in GitHub Desktop.
Typed Angular Environment
/***********************
* app-config.ts *
***********************/
import { InjectionToken } from '@angular/core'
export interface AppConfig {
production: boolean
apiURL: string
}
export const APP_CONFIG = new InjectionToken<AppConfig>('app.config')
/***********************
* app.module.ts *
***********************/
import { HttpClientModule } from '@angular/common/http'
import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { RouterModule } from '@angular/router'
import { APP_CONFIG, AppConfig } from '@core/config/app-config'
import { environment } from '@environment/environment'
import { AppRoutingModule } from './app-routing.module'
import { AppComponent } from './app.component'
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, RouterModule, HttpClientModule, AppRoutingModule],
bootstrap: [AppComponent],
providers: [
{ provide: APP_CONFIG, useValue: environment },
],
})
export class AppModule {}
/**********************
* Usage *
* asset.service.ts *
**********************/
import { HttpClient } from '@angular/common/http'
import { Inject, Injectable } from '@angular/core'
import { AppConfig, APP_CONFIG } from '@core/config/app-config'
import { Asset } from '@features/asset/interfaces'
import { Observable } from 'rxjs'
@Injectable({
providedIn: 'root',
})
export class AssetService {
private endpoint: string
constructor(
private http: HttpClient,
@Inject(APP_CONFIG) appConfig: AppConfig,
) {
this.endpoint = appConfig.apiURL + '/assets'
}
findById(id: string): Observable<Asset> {
return this.http.get<Asset>(`${this.endpoint}/${id}`)
}
delete(id: string): Observable<Asset> {
return this.http.delete(`${this.endpoint}/${id}`)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment