Using Angular environment variables in workspace libraries
Asked Answered
A

2

7

I am using workspaces concept of angular latest version(>6).

The CLI can generate a project that is a library with a command like this:

ng generate library api

tsconfig.json of default app is like this

"paths": {
      "env": ["src/environments"],
      "api": [
        "dist/api"
      ],

After that I created one service named ApiService in api library like this but it's not working

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'env';

@Injectable()
export class ApiService {
  constructor(private http: HttpClient) {}

  getApiUrl(){
    console.log("Hello Api Url"+environment.api_url)
}
}

Returns error when I build api library using command ng build api:

BUILD ERROR
error TS6059: File 'ROOT_APP_PATH/src/environments/environment.ts'
is not under 'rootDir' 'ROOT_APP_PATH\projects\api\src'.
'rootDir' is expected to contain all source files.

please help to resolve this error.

Thanks in Advance.

Algonquin answered 6/8, 2018 at 7:24 Comment(0)
K
0

You should add providedIn:

@Injectable({ providedIn: 'root' })

Kronos answered 6/8, 2018 at 9:8 Comment(3)
Thank for your suggestion but It's not working. BTW I understood this and I am able to build the library if I removed environment variable. So it's not about creating singleton service in root module. Also I am able to use that service in my root app. But when I tried getting environment variable in that library, I am getting this error.Algonquin
@NikhilChandu were you able to find any solution for this issue ? i have a couple of services to be imported into an angular library and i am facing the exact issue. any suggestions on how to fix this will be really helpful.Monaxial
You can make "rootDir": "." or like that "rootDir": "../" on your tsconfig.json.Kronos
C
0

By default rootDir is considered as the path of tsconfig.json

It Specifies the root directory of input files. Only use to control the output directory structure with --outDir.

compiler options

Cyclothymia answered 6/8, 2018 at 9:12 Comment(5)
I didn't get your point here. I have added environment in paths of root tsconfig.json as well, but it is searching environment variable in library root but not the root project.Algonquin
but environment path is by default configured in angular project. angular.jsonCyclothymia
there is no need to separately specify.Cyclothymia
Yes I agree with you. But I am not able to access that environment variable in my library. The same can be done using link. Please check this github link for sample example as well linkAlgonquin
Did you ever resolve this? I'm running into the same issue. (Typescript 3.1.1)Doxy

© 2022 - 2024 — McMap. All rights reserved.