App_base_href應用?

看到一個應用,是改變url的路徑,但不是用routing的方式做到
是在providers時增加APP_BASE_HREF去給他值

@NgModule({
   providers: [{provide: APP_BASE_HREF, useValue: '/test'}],
});
document.querySelector('base').href = `/test`;

我自己測試後發現,完全沒有像是他的範例那樣變更
不知道是我誤會他的用法還是寫錯了??

這是官方的介紹

The APP_BASE_HREF token represents the base href to be used with the PathLocationStrategy.
If you’re using PathLocationStrategy, you must provide a provider to a string representing the URL prefix that >should be preserved when generating and recognizing URLs.

你的index.html 是不是也有 base href阿?
他這個的目的主要是配合 HTML5 Path LocationStrategy 的要求,要設定 base href.
你檢查看看

有加base href,那執行完的話base href是會被改值
但網頁的url還是一樣的http://localhost:4200這樣
我以為會變成http://localhost:4200/test

我剛剛實驗了一下,如果 index.html 裡有 <base href="/"> 時,
Angular module 裡面設定 {provide: APP_BASE_HREF, useValue: '/test'} 就沒有用。

我用兩個專案有不同結果耶@@

  1. 加上bese href還是會加上/test再網址上

cli:1.0.0-rc.0
angular/core: 2.4.0

  1. 怎樣都不會加上/test

cli:1.0.0-beta.32.3
angular/core: 2.4.0

好奇了,這個值由程式直接修改
等於不管網站是什麼都要多一段,那這樣的應用情境是?

根據官網的寫法

The APP_BASE_HREF token represents the base href to be used with the PathLocationStrategy.

If you’re using PathLocationStrategy, you must provide a provider to a string representing the URL prefix that should be preserved when generating and recognizing URLs.

PathLocationStrategy API Doc

PathLocationStrategy is a LocationStrategy used to configure the Location service to represent its state in the path of the browser’s URL.

If you’re using PathLocationStrategy, you must provide a APP_BASE_HREF or add a base element to the document. This URL prefix that will be preserved when generating and recognizing URLs.

Location Service API Doc

Location is responsible for normalizing the URL against the application’s base href. A normalized URL is absolute from the URL host, includes the application’s base href, and has no trailing slash:

/my/app/user/123 is normalized
my/app/user/123 is not normalized
/my/app/user/123/ is not normalized

總結

設定 APP_BASE_HREF 的主要目的,就是為了 Location Service

1個讚