Angular 组件在 API 调用后未更新

Angular component doesn't update after API call

我有一个将模型作为 [输入] 的下拉组件。

在 parent 我有:

    public ngOnInit(): void {

        this.initializeDropdown();       
    }

private initializeDropdown(): void {

    this.viewModel.dropdownItems = {
        defaultItem: {
            display: 
            value: undefined
        },
        items: []
    };

    const promise = this.someService.get("SOMEURL");

    promise.then(res => {
        if (Array.isArray(res)) {

            res.map((item) => {

                this.viewModel.dropdownItems.items.push(
                    {
                        display: item.display,
                        value: item.value
                    });
                }
            );
        }
    });
}

问题是没有更新 child 组件。所以下拉列表不会更新。我可以看到 viewModel 已初始化。

我用一种方式绑定了它[this.viewModel.dropdownItems]

我也在其他地方使用这个下拉组件,所以我知道它有效。 (不知道 api 电话虽然不知道我是否在其他地方这样做)

如果您正在使用 changeDetection: ChangeDetectionStrategy.OnPush,请保留 ChangeDetectorRef 并调用 markForCheck,如下所示。

 constructor(private changeDetectorRef: ChangeDetectorRef) {}

 const promise = this.someService.get("SOMEURL");
    promise.then(res => {
        if (Array.isArray(res)) {

            res.map((item) => {

                this.viewModel.dropdownItems.items.push(
                    {
                        display: item.display,
                        value: item.value
                    });
                });
            this.changeDetectorRef.markForCheck();
        }
    });