【问题标题】:Angular 9 MatDatePicker + Internationalization Maximum call stack size exceededAngular 9 MatDatePicker + Internationalization 超出最大调用堆栈大小
【发布时间】:2020-04-29 21:45:04
【问题描述】:

我尝试在我的 Angular 9 应用程序中使用国际化,当我打开 datepicker 字段时,它在控制台中显示以下错误:

Console error screenshot

这是我的 DatePicker 适配器代码

import { Injectable } from '@angular/core';
import { NativeDateAdapter } from '@angular/material';
import { BehaviorSubject } from 'rxjs';


export const CUSTOM_DATE_FORMAT = {
    parse: {
        dateInput: null
    },
    display: {
        dateInput: 'CustomFormat',
        monthYearLabel: { year: 'numeric', month: 'short' },
        dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
        monthYearA11yLabel: { year: 'numeric', month: 'long' },
    }
};

export const datepicker: BehaviorSubject<string> = new BehaviorSubject('');

@Injectable()
export class Datepicker extends NativeDateAdapter {


    private subscription: any;

    format(date: Date, displayFormat?: string | object): string {
        if (!this.subscription) {
            this.subscription = datepicker.subscribe(v => {
                this.setLocale(v);
            });
        }

        if (this.locale === 'CustomFormat') {
            const day = date.getUTCDate();
            const month = date.getUTCMonth() + 1;
            const year = date.getFullYear();

            // Return the format as per your requirement
            return `${day}.${month}.${year}`;
        } else {
            // Refer to the standard formatting of the NativeDateAdapter.
            return super.format(date, displayFormat);
        }
    }

}

【问题讨论】:

    标签: angular datepicker angular-material


    【解决方案1】:

    如果您调用 setLocale 格式的 func 由于内部的更改触发器而再次被调用,那么您将永远无法摆脱这种情况,这会导致超出调用堆栈大小。

    将格式函数改为:

    format(date: Date, displayFormat?: string | Object): string {
        let loc = appLocale.getValue();
        if (this.locale !== loc)
            this.setLocale(loc);
        return super.format(date, displayFormat);
    }
    

    如果您订阅了一个 BehaviorSubject,即使它的值相同,您也会收到很多更改调用。

    您可以查看this one

    【讨论】:

    • 我正在查看您推荐的链接,但我不明白它是什么let loc = appLocale.getValue();
    • 我用同样的逻辑解决了问题,谢谢!
    猜你喜欢
    • 2020-06-07
    • 2020-10-27
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2015-10-24
    • 2015-12-29
    相关资源
    最近更新 更多