Angular 4 Routing - base-href被添加到hashPath之前

时间:2018-05-21 14:36:05

标签: angular lazy-loading angular4-router

当角度应用程序的内置版本放在根目录中时,它会生成网址

http://thisismydomain.com/#/master/data-source-management/data-sources/list

但是当它被放置在根目录的更深处,并且我使用base-href时,路由器在加载页面时仍然表现良好,但是一旦加载,base-href就会被添加到hashpath之前,如下所示:

http://thisismydomain.com/deeper/inside/#/deeper/inside/master/data-source-management/data-sources/list

预期网址:

http://thisismydomain.com/deeper/inside/#/master/data-source-management/data-sources/list

我发现问题与在app.module.ts的导入部分注入APP_BASE_HREF条目有关?

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:background="@null">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:background="@drawable/rect_background" />

    </LinearLayout>


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="fill_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"




        </LinearLayout>

    </ScrollView>

</LinearLayout>

注释出来解决了这个问题,但我需要它才能在我的服务中注入BASE_HREF来从assets文件夹中提取内容。 HELP?

P.S。我正在使用延迟加载。

1 个答案:

答案 0 :(得分:1)

我通过扩展HashLocationStrategy来创建一个CustomLocationStrategy来解决它,因为这似乎是唯一的解决方案。

import {Injectable} from '@angular/core';
import {HashLocationStrategy} from "@angular/common";

@Injectable()    
export class CustomLocationStrategy extends HashLocationStrategy {

  prepareExternalUrl(internal: string): string {
    const url = this.getBaseHref() + '#' + internal;
    return url;
  }
}

在app.module.ts中导入自定义类以及APP_BASE_HREF和LocationStrategy

import { APP_BASE_HREF, LocationStrategy } from "@angular/common";
import { CustomLocationStrategy } from './common/services/customLocationStrategy.service';

并在提供商部分添加了以下内容。

providers: [
  {
    provide: APP_BASE_HREF, 
    useValue: window.location.pathname
  }, 
  {
    provide: LocationStrategy, 
    useClass: CustomLocationStrategy
  }
]