Reputation: 189
Im new to Angular2, I have added some API configurations in environment file,its not giving any exception during compile time but getting exception at run time.
import { environment as defaultEnvironment } from './environment.defaults'
export const environment = {
...defaultEnvironment,
production: false,
apiService: {
serviceUrl: defaultEnvironment.baseURL + "TestService/",
getCompanies: this.serviceUrl + "GetCompanies",
}
};
At run time when its fetching value of serviceUrl in getCompanies, im getting exception "Uncaught TypeError: Cannot read property 'serviceUrl' of undefined"
Can anyone help to know why this is happening ? Thanks
Upvotes: 0
Views: 28
Reputation: 71941
Usually the this
has as type typeof globalThis
globalThis. Which I believe has as type any in a typescript environment. So that's why the compiler is not complaining (as long as you don't use strict: true
in typescript.
I suppose angular does things a bit differently in the environment files. These are specially parsed to be able to get replacement values in your codebase.
Nevertheless, what you are trying to do there will not work. this
will never be the object you are currently constructing. You will need to split that up:
import { environment as defaultEnvironment } from './environment.defaults'
const serviceUrl = defaultEnvironment.baseURL + "TestService/";
export const environment = {
...defaultEnvironment,
production: false,
apiService: {
serviceUrl,
getCompanies: serviceUrl + "GetCompanies",
}
};
Upvotes: 1