【问题标题】:Angular: resolve rendering in subscribeAngular:解决订阅中的渲染
【发布时间】:2020-04-28 05:14:20
【问题描述】:

我想在“noRender”更改时对 DOM 进行一些更改。 'noRender' 隐藏所有 DOM 并在 subscribe 方法中更改。我试过'onChanges' - 它没有用。我决定在 subscribe 方法里面写代码,但是在 subscribe 方法完成之后才执行重新渲染。怎么解决?请帮忙

this.http.post(Main.BASE_URL + StaticData.SIGN_URL, {})
  .subscribe((value: Response) => {
    this.noRender = false;
    if(document.querySelector('.steps-list-line')){
        (document.querySelector('.steps-list-line') as HTMLElement).style.width =
        (document.querySelector('.active') as HTMLElement).offsetWidth +
        (document.querySelector('.active') as HTMLElement).offsetLeft + 'px';
    }
  } 
});

【问题讨论】:

  • 你到底想做什么改变?什么时候?

标签: angular typescript


【解决方案1】:

示例 1

要检测noRender 变量中值的变化,您可以将此变量的类型更改为BehaviorSubject<boolean>。因此,您有机会订阅数据流。

export class SomeComponent{

    noRender = new BehaviorSubject<boolean>(false);

    constructor() {
        this.noRender.subscribe((newValue) => {
            // handle value changed
        });
    }

    someAction() {
        // change value of the noRender subject
        this.noRender.next(true);
    }

}

示例 2

如果noRender 变量是输入属性,您可以使用property-watch-decorator(链接:https://www.npmjs.com/package/property-watch-decorator),它允许检测输入属性的变化。

export class SomeComponent{

    @OnChange(function(this: SomeComponent, newValue: boolean){
        // handle value changed
    })
    @Input() noRender: boolean;

}

【讨论】:

  • 其实是html中有ngif,这取决于'noRender'参数。订阅方法在重新渲染之前执行。因此,无法对 subscribe 内部的 DOM 进行更改。您认为如何解决这个问题?
  • 您可以使用Async pipe,而不是在构造函数中进行订阅,它将自动订阅该主题并在发出新值时自动更新模板。示例:&lt;div *ngIf="noRender | async"&gt;&lt;/div&gt;
  • 我需要以下顺序: 1. noRender 参数更改 2. 由于 noRender 参数的更改发生了重新渲染 3. 我用 javascript 更改了 DOM 我不知道在什么时刻执行第3点,因为在上述改变noRender的时刻,subscribe方法首先执行,然后发生re-rednering。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-17
  • 2017-07-29
  • 1970-01-01
  • 1970-01-01
  • 2015-09-26
  • 2020-10-11
  • 2014-02-12
相关资源
最近更新 更多