Looking to streamline API data sharing across a sample app, I attempted two versions of a Class creation but encountered issues with one of them:
Version 1 [./apiKeys.ts] - working
import {Injectable} from '@angular/core';
@Injectable()
export class SomeApi{
key: string;
url: string;
constructor(){
this.key = 'API_KEY';
this.url = 'API_URL';
}
}
Version 2 [./apiKeys.ts] - not working
import {Injectable} from '@angular/core';
@Injectable()
export class SomeApi{
constructor(
public key:string = 'API_KEY',
public url:string = 'API_URL'
){}
}
The plan is to pass it as a provider at bootstrapping time
./main.ts
import {SomeApi} from './apiKeys.ts'
bootstrap(AppComponent, [SomeApi])
However, upon startup, the following error occurs (for version 2):
ORIGINAL EXCEPTION: No provider for String! (SomeApi -> String)
What might be causing version 2 to fail? Many thanks
EDIT
Following suggestions by Günter Zöchbauer, I consulted various resources and implemented what appears to be the optimal solution in my case. Here's what was done:
./apiKeys.ts
import { OpaqueToken } from '@angular/core';
export interface AppConfig{
key: string;
url: string;
}
export const DI_CONFIG: AppConfig = {
key: 'AIzaSyAjC3U-CbKYm_4sYV90XqJ_Upe8ID9jlxk',
url: 'https://www.googleapis.com/youtube/v3/search'
}
export let APP_CONFIG = new OpaqueToken('app.config');
./main.ts
import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
import {DI_CONFIG, APP_CONFIG} from './apiKeys';
bootstrap(AppComponent, [{ provide: APP_CONFIG, useValue: DI_CONFIG }]);
./apiService.ts
import {Injectable, Inject} from '@angular/core';
import {APP_CONFIG, AppConfig} from './apiKeys';
@Injectable()
export class ApiService{
constructor(
@Inject(APP_CONFIG) private config: AppConfig
){}
// Access properties using this.config.url or this.config.key
}
Sources: