Slim 3 + Pleague 2.4 - Alias (router) is not being managed by the container? - ioc-container

How do I use Pleaguev2.4 with Slim v3.8.1?
Following this example, I tried:
// PSR 7 standard.
use Slim\Http\Request;
use Slim\Http\Response;
// Import classes.
use Slim\App as Slim;
use League\Container\Container;
$container = new Container;
// Required to enable auto wiring.
$container->delegate(
new \League\Container\ReflectionContainer
);
// Get an instance of Slim.
$app = new Slim($container);
I get:
Fatal error: Uncaught League\Container\Exception\NotFoundException:
Alias (router) is not being managed by the container in
/var/www/html/projectA/vendor/league/container/src/Container.php:266
Stack trace: #0
/var/www/html/projectA/vendor/league/container/src/Container.php(93):
League\Container\Container->getFromDelegate('router', Array) #1
/var/www/html/projectA/vendor/slim/slim/Slim/App.php(239):
League\Container\Container->get('router') #2
/var/www/html/projectA/vendor/slim/slim/Slim/App.php(143):
Slim\App->map(Array, '/', Object(Closure)) #3
/var/www/html/projectA/public/index.php(53): Slim\App->get('/',
Object(Closure)) #4 {main} thrown in
/var/www/html/projectA/vendor/league/container/src/Container.php on
line 266
Any ideas?

Slim is trying to access the router which isn't defined on the container you've added. In Slim they will be added by the \Slim\DefaultServicesProvider.
But you cannot use it because your DI Container doesn't support array access.
An option to fix this problem is to set the Slim container as delegate, then the League\Container\Container will get the router and all other stuff through the slim container:
$container = new \League\Container\Container;
$container->delegate(new \Slim\Container());
$app = new \Slim\App($container);

Related

What are cloudflare KV preview_ids and how to get one?

I have a following wrangler.toml. When I would like to use dev or preview (e.g. npx wrangler dev or npx wrangler preview) wrangler asks to add a preview_id to the KV namespaces. Is this an identifier to an existing KV namespace?
I see there is a ticket in Cloudflare Workers GH at https://github.com/cloudflare/wrangler/issues/1458 that tells this ought to be clarified but the ticket is closed with adding an error message
In order to preview a worker with KV namespaces, you must designate a preview_id in your configuration file for each KV namespace you'd like to preview."
which is the reason I'm here. :)
As for larger context I would be really glad if someone could clarify: I see that if I give a value of an existing namespace, I can preview and I see a KV namespace of type __some-worker-dev-1234-workers_sites_assets_preview is generated in Cloudflare. This has a different identifier than the KV namespace pointed by the identifier used in the preview_id and the KV namespace pointed by the identifier I used in preview_id is empty. Why does giving an identifier of an existing KV namespace remove the error message, deploys the assets and allow for previwing but the actual KV namespace is empty and a new one is created?
How do does kv-asset-handler know to look into this generated namespace to retrieve the assets?
I'm currently testing with the default generated Cloudare Worker to my site and I wonder if I have misunderstood something or if there is some mechanics that bundles during preview/publish the site namespace to the scipt.
If there is some random mechanics with automatic mapping, can this be then so that every developer can have their own private preview KV namespace?
type = "javascript"
name = "some-worker-dev-1234"
account_id = "<id>"
workers_dev = true
kv_namespaces = [
{ binding = "site_data", id = "<test-site-id>" }
]
[site]
# The location for the site.
bucket = "./dist"
# The entry directory for the package.json that contains
# main field for the file name of the compiled worker file in "main" field.
entry-point = ""
[env.production]
name = "some-worker-1234"
zone_id = "<zone-id>"
routes = [
"http://<site>/*",
"https://www.<site>/*"
]
# kv_namespaces = [
# { binding = "site_data", id = "<production-site-id>" }
# ]
import { getAssetFromKV, mapRequestToAsset } from '#cloudflare/kv-asset-handler'
/**
* The DEBUG flag will do two things that help during development:
* 1. we will skip caching on the edge, which makes it easier to
* debug.
* 2. we will return an error message on exception in your Response rather
* than the default 404.html page.
*/
const DEBUG = false
addEventListener('fetch', event => {
try {
event.respondWith(handleEvent(event))
} catch (e) {
if (DEBUG) {
return event.respondWith(
new Response(e.message || e.toString(), {
status: 500,
}),
)
}
event.respondWith(new Response('Internal Error', { status: 500 }))
}
})
async function handleEvent(event) {
const url = new URL(event.request.url)
let options = {}
/**
* You can add custom logic to how we fetch your assets
* by configuring the function `mapRequestToAsset`
*/
// options.mapRequestToAsset = handlePrefix(/^\/docs/)
try {
if (DEBUG) {
// customize caching
options.cacheControl = {
bypassCache: true,
}
}
const page = await getAssetFromKV(event, options)
// allow headers to be altered
const response = new Response(page.body, page)
response.headers.set('X-XSS-Protection', '1; mode=block')
response.headers.set('X-Content-Type-Options', 'nosniff')
response.headers.set('X-Frame-Options', 'DENY')
response.headers.set('Referrer-Policy', 'unsafe-url')
response.headers.set('Feature-Policy', 'none')
return response
} catch (e) {
// if an error is thrown try to serve the asset at 404.html
if (!DEBUG) {
try {
let notFoundResponse = await getAssetFromKV(event, {
mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/404.html`, req),
})
return new Response(notFoundResponse.body, { ...notFoundResponse, status: 404 })
} catch (e) {}
}
return new Response(e.message || e.toString(), { status: 500 })
}
}
/**
* Here's one example of how to modify a request to
* remove a specific prefix, in this case `/docs` from
* the url. This can be useful if you are deploying to a
* route on a zone, or if you only want your static content
* to exist at a specific path.
*/
function handlePrefix(prefix) {
return request => {
// compute the default (e.g. / -> index.html)
let defaultAssetKey = mapRequestToAsset(request)
let url = new URL(defaultAssetKey.url)
// strip the prefix from the path for lookup
url.pathname = url.pathname.replace(prefix, '/')
// inherit all other props from the default request
return new Request(url.toString(), defaultAssetKey)
}
}
In case the format is not obvious (it wasn't to me) here is a sample config block from the docs with the preview_id specified for a couple of KV Namespaces:
kv_namespaces = [
{ binding = "FOO", id = "0f2ac74b498b48028cb68387c421e279", preview_id = "6a1ddb03f3ec250963f0a1e46820076f" },
{ binding = "BAR", id = "068c101e168d03c65bddf4ba75150fb0", preview_id = "fb69528dbc7336525313f2e8c3b17db0" }
]
You can generate a new namespace ID in the Workers KV section of the dashboard or with the Wrangler CLI:
wrangler kv:namespace create "SOME_NAMESPACE" --preview
This answer applies to versions of Wrangler >= 1.10.0
wrangler asks to add a preview_id to the KV namespaces. Is this an identifier to an existing KV namespace?
Yes! The reason there is a different identifier for preview namespaces is so that when developing with wrangler dev or wrangler preview you don't accidentally write changes to your existing production data with possibly buggy or incompatible code. You can add a --preview flag to most wrangler kv commands to interact with your preview namespaces.
For your situation here there are actually a few things going on.
You are using Workers Sites
You have a KV namespace defined in wrangler.toml
Workers Sites will automatically configure a production namespace for each environment you run wrangler publish on, and a preview namespace for each environment you run wrangler dev or wrangler preview on. If all you need is Workers Sites, then there is no need at all to specify a kv-namepsaces table in your manifest. That table is for additional KV namespaces that you may want to read data from or write data to. If that is what you need, you'll need to configure your own namespace and add id to wrangler.toml if you want to use wrangler publish, and preview_id (which should be different) if you want to use wrangler dev or wrangler preview.

Scheduling localhost serverless cron: The model could not be resolved in registry

I'm hosting an ExpressJS/NodeJS API on AWS Lambda with Serverless framework. The API uses Knex.js and Bookshelf.js ORM.
I want to test scheduling a cron job locally. I'm using serverless-offline-scheduler to do this.
Question: My API runs fine if I call it from my client, but if I call a function via serverless scheduler, it complains that no models are in the registry. Why is this? I've already definitely included all necessary Models at the top of the OrderService.js file.
{
"errorMessage": "The model User could not be resolved from the registry plugin.",
"errorType": "Error",
"stackTrace": [
"Error: The model User could not be resolved from the registry plugin.",
" at new ModelNotResolved (/Users/danielturcotte/Sites/d2c/api_v4/node_modules/bookshelf/lib/plugins/registry.js:70:133)",
Serverless.yml:
functions:
app:
handler: handler.handler
events: ...
dequeue:
handler: ./services/OrderService.dequeue // Call dequeue function
events:
- schedule: rate(1 minute)
The handler calls root/services/OrderService.dequeue function, which contains
...
const dequeue = async function() {
await checkQueuedOrders();
};
module.exports = {
dequeue,
};
In my knexService.js file, I register Bookshelf models to the registry to remove circular dependencies:
const knexfile = require('./knexfile');
const config = require('./environment');
const environment = config.env.NODE_ENV || 'development';
const knex = require('knex')(knexfile[environment]);
knex.client.pool.numPendingCreates();
const bookshelf = require('bookshelf')(knex);
bookshelf.plugin('registry'); // Resolve circular dependencies with relations
bookshelf.plugin('visibility');
bookshelf.plugin('pagination');
module.exports.knex = knex;
module.exports.bookshelf = bookshelf;

Symfony - No Extension Is Able To Load The Configuration (Subscriber/Event Listening) (REST API Exception Handling with JSON output)

Purpose
Hello, I am fairly new to Symfony and am trying to create an exception/error handling functionality for our Web API.
Requirements
When a user makes an invalid request to our API, we want to return a simple JSON object that looks something like the following:
{"errorCode": 1234567, "errorMessage": "Parameter 1 is invalid. String expected"}
In addition to API-specific errors, we also want to hook into the built-in exception-handling in Symfony and re-use that, but instead of returning an HTML error page (which is what happens by default), we want to return a JSON object like:
{"errorCode": 404, "errorMessage": "Not found"}
Current Approach
Obviously, we want this to be implemented in the most efficient way, so after doing some research, I found what I think is a great approach which I can then adapt to our specific needs. Here is the tutorial I followed:
https://knpuniversity.com/screencast/symfony-rest2
I ended up buying this course in order to get access to the full code. The issue is that it was written for Symfony 2, but we are running Symfony 3.3, so some things are outdated and I have not been able to get the example running yet.
Code
So, I have posted some of the relevant code below. (I obviously cannot post the whole code, but have posted what are hopefully the relevant portions of the publicly-available code).
services.yml (Their version, Symfony 2 Style)
api_exception_subscriber:
class: AppBundle\EventListener\ApiExceptionSubscriber
arguments: []
tags:
- { name: kernel.event_subscriber }
services.yml (my full file with all comments removed)
This includes a modified version of what they have above (hopefully this is the correct Symfony 3.3 way of doing things).
NOTE: Anything that was part of the private code which I cannot show, I have replaced with the word "something".
parameters:
services:
_defaults:
autowire: true
autoconfigure: true
public: false
AppBundle\:
resource: '../../src/AppBundle/*'
exclude: '../../src/AppBundle/{Entity,Repository,Tests}'
AppBundle\Controller\:
resource: '../../src/AppBundle/Controller'
public: true
tags: ['controller.service_arguments']
AppBundle\EventListener\ApiExceptionSubscriber:
arguments:
- ['%something.something%']
tags:
- {name: 'kernel.event_subscriber'}
routing.yml (relevant section of their file)
app_api:
resource: "#AppBundle/Controller/Api"
type: annotation
defaults:
_format: json
routing.yml (my full file) - NOTE: I had to add the "_format: json" directly to the "app" section here rather than "app_api" because in our REST API, all of our URLs are at the root level, and do NOT have to be prefixed with "api" like http://localhost/api/someMethod/someMethodParameter as in the tutorial's code
app:
resource: '#AppBundle/Controller/'
type: annotation
defaults: {_format:json}
yml_route:
path: /yml-route
defaults:
_controller: AppBundle:Default:yml
awesome_route:
path: /awesome-route/{ic}
defaults:
_controller: AppBundle:Rest:awesomeRoute
src/AppBundle/RestController.php (edited to show just the basic structure)
<?php
namespace AppBundle\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\HttpFoundation\Request;
class RestController extends Controller {
public function doSomething($id)
{
// Code to populate $result with data from database is here
return new JsonResponse($result);
}
// This file contains many different functions similar to doSomething() which retrieve the request for the API caller.
// For example, doSomething() can be accessed via http://localhost/app_dev.php/doSomething/123
}
src/AppBundle/Api/ApiProblem.php (edited to show just the basic structure)
namespace AppBundle\Api;
use Symfony\Component\HttpFoundation\Response;
class ApiProblem
{
// Code relevant to this class is in here
}
src/AppBundle/Api/ApiProblemException.php (edited to show just the basic structure)
<?php
namespace AppBundle\Api;
use Symfony\Component\HttpKernel\Exception\HttpException;
class ApiProblemException extends HttpException
{
private $apiProblem;
public function __construct($severalParametersWhichICannotListHereBecauseCodeIsPrivate) {
// Does some stuff and then calls the parent:__construct
// Includes a getter for $apiProblem
}
}
src/AppBundle/EventListener/ApiExceptionSubscriber.php (edited to show just the basic structure)
<?php
namespace AppBundle\EventListener;
use AppBundle\Api\ApiProblem;
use AppBundle\Api\ApiProblemException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\KernelEvents;
class ApiExceptionSubscriber implements EventSubscriberInterface
{
// Code relevant to this subscriber is here
}
The Issue
I'm getting the following error when I try to run any type of command from the command-line bin/console:
C:\htdocs\projects\myproject>php bin/console debug:container
PHP Fatal error: Uncaught Symfony\Component\DependencyInjection\Exception\InvalidArgumentException: T
here is no extension able to load the configuration for "AppBundle\EventListener\ApiExceptionSubscribe
r" (in C:\htdocs\projects\myproject\app/config\services.yml). Looked for namespace "AppBundle\EventListe
ner\ApiExceptionSubscriber", found "framework", "security", "twig", "monolog", "swiftmailer", "doctrin
e", "sensio_framework_extra", "demontpx_parsedown", "doctrine_cache", "doctrine_migrations", "debug",
"web_profiler", "sensio_distribution", "web_server" in C:\htdocs\projects\myproject\vendor\symfony\symfo
ny\src\Symfony\Component\DependencyInjection\Loader\YamlFileLoader.php:644
Stack trace:
#0 C:\htdocs\projects\myproject\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Loader\
YamlFileLoader.php(614): Symfony\Component\DependencyInjection\Loader\YamlFileLoader->validate(Array,
'C:\\htdocs\\proje...')
#1 C:\htdocs\projects\myproject\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Loader\
YamlFileLoad in C:\htdocs\projects\myproject\vendor\symfony\symfony\src\Symfony\Component\Config\Loader\
FileLoader.php on line 179
Fatal error: Uncaught Symfony\Component\DependencyInjection\Exception\InvalidArgumentException: There
is no extension able to load the configuration for "AppBundle\EventListener\ApiExceptionSubscriber" (i
n C:\htdocs\projects\myproject\app/config\services.yml). Looked for namespace "AppBundle\EventListener\A
piExceptionSubscriber", found "framework", "security", "twig", "monolog", "swiftmailer", "doctrine", "
sensio_framework_extra", "demontpx_parsedown", "doctrine_cache", "doctrine_migrations", "debug", "web_
profiler", "sensio_distribution", "web_server" in C:\htdocs\projects\myproject\vendor\symfony\symfony\sr
c\Symfony\Component\Config\Loader\FileLoader.php on line 179
Symfony\Component\Config\Exception\FileLoaderLoadException: There is no extension able to load the con
figuration for "AppBundle\EventListener\ApiExceptionSubscriber" (in C:\htdoc
fig\services.yml). Looked for namespace "AppBundle\EventListener\ApiExceptio
work", "security", "twig", "monolog", "swiftmailer", "doctrine", "sensio_fra
arsedown", "doctrine_cache", "doctrine_migrations", "debug", "web_profiler",
eb_server" in C:\htdocs\projects\myproject\app/config\services.yml (which is b
ocs\projects\myproject\app/config\config.yml"). in C:\htdocs\projects\myproject\
\Symfony\Component\Config\Loader\FileLoader.php on line 179
Call Stack:
1.4353 6149416 1. Symfony\Component\Debug\ErrorHandler->handleExcep
myproject\vendor\symfony\symfony\src\Symfony\Component\Debug\ErrorHandler.php:
What I've Tried
I've been debugging this for the last several days and have read many related discussions on Stack Overflow. I'm fairly new to services, subscribers, and dependency injection and I've tried editing both the routes.yml and services.yml numerous times. I was also getting some circular reference exceptions before but think I've fixed those now. I was hoping someone could please provide me with some direction and hopefully help me turn this into a working example on Symfony 3.3 that I can learn from. If you need any additional detail, please let me know.
From what I've learned, autowiring/autoconfiguring of services in Symfony 3.3 seems to be new and I think that may be impacting things but I'm not sure. I did try turning both of those settings off in services.yml though but with no luck.

deepstream error listen EADDRINUSE 127.0.0.1:6020

i try to run my first deepstream.io server from this link but i get this error :
error:
CONNECTION_ERROR | Error: listen EADDRINUSE 127.0.0.1:3003
PLUGIN_ERROR | connectionEndpoint wasn't initialised in time
f:\try\deep\node_modules\deepstream.io\src\utils\dependency-
initialiser.js:96
throw error
^
Error: connectionEndpoint wasn't initialised in time
at DependencyInitialiser._onTimeout
(f:\try\deep\node_modules\deepstream.io\src\utils\dependency-
initialiser.js:94:17)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
and this is my code:
const DeepStreamServer = require("deepstream.io")
const C = DeepStreamServer.constants;
const server = new DeepStreamServer({
host:'localhost',
port:3003
})
server.start();
In deepstream 3.0 we released our HTTP endpoint, by default this runs alongside our websocket endpoint.
Because of this, passing the port option at the root level of the config no longer works (it overrides both the HTTP and websocket port options, as you can see in the screen capture provided, both endpoints are trying to start on the same port).
You can override each of these ports as follows:
const deepstream = require('deepstream.io')
const server = new deepstream({
connectionEndpoints: {
http: {
options: {
port: ...
}
},
websocket: {
options: {
port: ...
}
}
}
})
server.start()
Or you can define your config in a file and point to that while initialising deepstream[1].
[1] deepstream server configuration
One solution that i find is passing empty config object so inseted of :
const server = new DeepStreamServer({
host:'localhost',
port:3003
})
i'm just using this :
const server = new DeepStreamServer({})
and now everything work's well.
All the bellow is for Version 4.2.2 (last version by now)
I was having the same Port in use or config file not found errors. And i was using typescript and i didn't pay attention too to the output dir and build (which can be a problem when one use typescript and build). I was able to run the server in the end. And i had a lot of analysis.
I checked up the code source and i have seen how the config is loaded
const SUPPORTED_EXTENSIONS = ['.yml', '.yaml', '.json', '.js']
const DEFAULT_CONFIG_DIRS = [
path.join('.', 'conf', 'config'), path.join('..', 'conf', 'config'),
'/etc/deepstream/config', '/usr/local/etc/deepstream/config',
'/usr/local/etc/deepstream/conf/config',
]
DEFAULT_CONFIG_DIRS.push(path.join(process.argv[1], '..', 'conf', 'config'))
DEFAULT_CONFIG_DIRS.push(path.join(process.argv[1], '..', '..', 'conf', 'config'))
Also i tested different things and all. Here what i came up with:
First of all if we don't precise any parameter in the constructor. A config from the default directories will get to load. If there isn't then the server fail to run.
And one of the places where we can put a config is ./conf in the same folder as the server node script.
Secondly we can precise a config as a string path (parameter in the constructor). config.yml or one of the supported extensions. That will allow the server to load the server config + the permission.yml and users.yml configs. Which too are supposed to be in the same folder. If not in the same folder there load will fail, and therefor the permission plugin will not load. And so does the users config. And no fall back to default will happen.
Thirdly the supported extensions for the config files are: yml, yaml, json, js.
In nodejs context. If nothing precised. There is no fallback to some default config. The config need to be provided in one of the default folders, or by precising a path to it. Or by passing a config object. And all the optional options will default to some values if not provided ( a bit bellow there is an example that can show that ). Know however that precising an end point is very important and required.
To precise the path, we need to precise the path to the config.yml file (the server config) [example: path.join(__dirname, './conf/config.yml')]. Then from the same dir permission.yml and users.yml will be retrieved (the extension can be any of the supported one). We can not precise a path to a directory, it will fail.
We can precise the path to permission config or user config separatly within config.yaml as shown bellow:
# Permissioning example with default values for config-based permissioning
permission:
type: config
options:
path: ./permissions.yml
maxRuleIterations: 3
cacheEvacuationInterval: 60000
Finally we can pass an object to configure the server, or by passing null as a parameter and use .set methods (i didn't test the second method). For configuring the server we need to follow the same structure as the yml file. With sometimes a bit different naming. The typescript declaration files or types show us the way. With an editor like vscode. Even if we are not using typescript we can keep get the auto completion and type definitions.
And the simplest for equivalent to the previous version is :
const webSocketServer = new Deepstream({
connectionEndpoints: [
{
type: 'ws-websocket',
options: {
port: 6020,
host: '127.0.0.1',
urlPath: '/deepstream'
}
}
]
});
webSocketServer.start();
the above is the new syntax and way.
const server = new DeepStreamServer({
host:'localhost',
port:3003
})
^^^^^^^ is completely deprecated and not supported in version 4 (the doc is not updated).

Angular 2 testing - process.env

I try to mock requests in my application, but there is a problem with process variable. I store in process.env.backendUrl url to backend API. And then in RestService I have:
constructor(private http: Http) {
this.rest = process.env.backendUrl + "/api/";
}
And now it is impossible to run tests because in for example LoginComponent I have RestService dependency and I've got this error:
zone.js:140 Uncaught Error: Error in ./LoginComponent class LoginComponent_Host - inline template:0:0 caused by: process is not defined
ReferenceError: process is not defined
at new RestService (http://localhost:9876/base/src/test.ts:21595:2790)
at DynamicTestModuleInjector.get (DynamicTestModule.ngfactory.js:170:67)
at DynamicTestModuleInjector.get (DynamicTestModule.ngfactory.js:180:93)
at DynamicTestModuleInjector.getInternal (DynamicTestModule.ngfactory.js:255:51)
at DynamicTestModuleInjector.NgModuleInjector.get (http://localhost:9876/base/src/test.ts:25036:27)
at TestBed.get (http://localhost:9876/base/src/test.ts:5589:51)
at _View_LoginComponent_Host0.createInternal (LoginComponent_Host.ngfactory.js:16:74)
at _View_LoginComponent_Host0.AppView.create (http://localhost:9876/base/src/test.ts:36192:21)
at _View_LoginComponent_Host0.DebugAppView.create (http://localhost:9876/base/src/test.ts:36404:44)
I set proccess.env.backendUrl in enviroment.ts (file created by angular-cli).
process.env.backendUrl = 'http://localhost:8080';
export const environment = {
production: false
};
Should I set it somewhere else or is there any method to tell karma about this variable?
If you're using angular-cli, you should just add the backendUrl to the environment.
export const environment = {
production: false,
backendUrl: 'http://localhost:8080'
};
You should also add it in the environment.prod.ts file, setting the url to the production url. When you build in production, the .prod file will be used.
In your files, you should import the environment (from the environment.ts file) and just use environment.backendUrl.
See Also:
Build Targets and Environment Files