Angular 8 baseUrl gets wiped out

610 Views Asked by At

What we try to do is integrate and angular app in a PHP environment. So the site will completely run on PHP for the static context, only when the user clicks on login, the will end up in the angular part.

So, now the problem. When we enter the URL in PHP, it will be something like ...domain/nl/page. So far so good, and this get redirected to angular, also this works, angular load. But then angular deletes the last part of the link and changes it to

...domain/{pageThatAngularIsIn}.

This is where we want to keep the language en the URL should be

.../domain/nl/{pageThatAngularIsIn} or even 
.../domain/nl/page/{pageThatAngularIsIn}  -> step by step

So angular should ignore the language part in the URL but also not wipe it form the URL.

Anybody know if this is possible of why this happens?

1

There are 1 best solutions below

1
BeetleJuice On

Your problem is probably happening because Angular thinks that domain/ is the base route on which it should append its own routing. From your description, it sounds like you wan the base route to be domain/nl/ instead.

This is a simple fix. In the index.html file that has your angular root component embedded, look for a base element in the head and set it to the base path. By default, it's usually something like this:

<base href="/">

Experiment with it to get what you need. Perhaps:

<base href="/nl">

See the docs

If you will need to use that same base within your angular app, for instance to make http calls in a way that will use the same base, you should probably use the APP_BASE_HREF in your root module providers instead. Like:

import {Component, NgModule} from '@angular/core';
import {APP_BASE_HREF} from '@angular/common';

@NgModule({
  ...
  providers: [{provide: APP_BASE_HREF, useValue: '/nl'}]
})
class AppModule {}

With this you will be able to inject the base in your services, for example to make your http calls.

@Injectable()
export class MyService {
  constructor(
    private http: HttpClient, 
    @Inject(APP_BASE_HREF) private baseHref: string
  ) {}

  getRecords() {
    return this.http.get(this.baseHref + '/records')
  }
}

See the docs