Angular CLI 產生的前端程式一般而言無法正確在 IE 瀏覽器執行,主要有幾個原因:
- polyfill.ts 必須要修改內容:
Polyfill 本身的目的就是提供一個中介API層,讓舊的瀏覽器可以支援新的API,Angular CLI 自帶的 polyfill.ts (在 src/ 目錄下),預設會註解掉 IE 的支援,將其移除即可(以下還多增加 es7/array 的支援):
/** IE9, IE10 and IE11 requires all of the following polyfills. **/ import 'core-js/es6/symbol'; import 'core-js/es6/object'; import 'core-js/es6/function'; import 'core-js/es6/parse-int'; import 'core-js/es6/parse-float'; import 'core-js/es6/number'; import 'core-js/es6/math'; import 'core-js/es6/string'; import 'core-js/es6/date'; import 'core-js/es6/array'; import 'core-js/es6/regexp'; import 'core-js/es6/map'; import 'core-js/es6/weak-map'; import 'core-js/es6/set'; /** IE10 and IE11 requires the following for NgClass support on SVG elements */ // import 'classlist.js'; // Run `npm install --save classlist.js`. /** IE10 and IE11 requires the following for the Reflect API. */ import 'core-js/es6/reflect'; /** Evergreen browsers require these. **/ // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove. import 'core-js/es7/reflect'; import 'core-js/es7/array';
- 不可以使用 angular 的 forEach
forEach() loop 是 Angular 所提供一個很好的服務,他支援 Async 方式解析陣列的元件;但可惜 IE 11 不支援,因此,若程式需要支援 IE 11,必須要將 forEach() 寫法轉成標準的 for loop。
舉例如下,正常而言,透過 angular forEach 可以直接瀏覽陣列元素:
selections.forEach(item => this.get(item.ItemType, item.ParentCode, item.NeedEmpty) .subscribe(data => item.Details = data) );
一個很重要的議題在於處理 subscribe 針對 http async 的回傳元件,forEach 可以確保 subscribe 中的 item 的值會是當下的 item,如果一般的 loop:
for (var i = 0; i < selections.length; i++) {
var item = selections[i];
this.get(item.ItemType, item.ParentCode, item.NeedEmpty)
.subscribe(data => item.Details = data)
這樣寫法是會錯誤的,因為 item 會永遠是最後一筆!
需要改為 透過 function 來設定 item 的內容:
for (var i = 0; i < selections.length; i++) {
var item = selections[i];
this.get(item.ItemType, item.ParentCode, item.NeedEmpty, item);
}
get(key, parentCode, needEmpty, codeFile: CodeFile): void {
this.http.get<Code[]>(this.baseUrl)
.subscribe(response => {
let items: Code[] = <Code[]>response;
codeFile.Details = items;
this.selections.push(codeFile);
});
}
- Cache 問題:IE 預設會自帶 Cache, 會造成 Angular httpClient 的讀取都是回傳 Cache 的值,因此造成明明有變更但頁面卻無法顯示。解決方式是加上 HttpHeaders diable Cache:
private noCacheHeader: HttpHeaders = new HttpHeaders().set('Cache-Control', 'no-cache').set('Pragma', 'no-cache');
public getDailyReport(id: number): Observable<DailyReportItem> {
let params = new HttpParams().set('id', id.toString());
return this.http.get<DailyReportItem>("/dailyreport/getreport", { params: params, headers: this.noCacheHeader });
}
這裡必須要加入 Cache-Control + Pragma 兩個設定。
