base href is case sensitive in Angular 2

情到浓时终转凉″ 提交于 2019-12-11 07:04:00

问题


I have set the base ref like this for an Angular 2 app

<base href="MyApp"/>

If I go to localhost/MyApp everything works correctly. However, if I go to localhost/myapp the route is not recognised. How can I tell Angular to treat the base route as case insensitive?


回答1:


You will have to write code to override base href.

Possible locations you can override is 1. Angular2: Make route paths case insensitive

  1. You write your own location strategy & Ignore case sensitivity there. And in your app.module.ts, you tell ur Angular 2 app to use custom location strategy in your providers section.

    {provide:LocationStrategy,useClass:CustomPlatformLocation},




回答2:


I tried Parth way, but I couldn't find a way to fix my problem with the LocationStrategy approach.

Based on some ideas from this question and ended up with something like this:

import { DefaultUrlSerializer, UrlTree } from "@angular/router";

export class LowercaseUrlSerializer extends DefaultUrlSerializer {

    parse(url: string): UrlTree {

        let urlUpperBaseUrl = url;

        if (url.startsWith("/app")) {
            urlUpperBaseUrl = "/APP" + url.slice(4);
        }
        if (url.startsWith("app")) {
            urlUpperBaseUrl = "APP" + url.slice(3);
        }

        return super.parse(urlUpperBaseUrl);
    }

}

You have to configure the injector as well:

@NgModule({
    ...
    providers: [
        ...
        { provide: UrlSerializer, useClass: LowercaseUrlSerializer },
    ],
    ...
})
export class AppModule {
}

I hope it hepls!




回答3:


I added typed base href as a route in router config with redirectTo property set to default route of the app, which is in my case is 'login', so any combination of base href will work. This is more sort of a hack.

I wrote that code in the app.component.ts file.

ngOnInit() {
   var baseHref  = window.location.pathname.split('/')[1];
   if(baseHref != "" && baseHref != "login")
      this.router.config.Add({path:baseHref,redirectTo:'/login',pathMatch:'full'});
}

Note:- As suggested by other answers, LowerCaseUrlSerializer didn't work for me as it requires all routes specified in my app to be in lower case only.




回答4:


using <base href="./"> instead of <base href="MyApp"/> (implicit) solved the problem for me. the virtual directory now is case insensitive.



来源:https://stackoverflow.com/questions/41742651/base-href-is-case-sensitive-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!