Angular 8:我们如何检测组件的重新渲染(作为事件)?

3
我需要一个事件来捕获Angular 8中组件的重新渲染。

请问您能否提供更多细节? - undefined
我通过HttpClient发送一个请求。当我收到响应时,状态会被更新并且组件会重新渲染。我需要捕捉到这个重新渲染的时刻。 - undefined
请检查答案并添加一些代码示例。 - undefined
1个回答

1
我认为如果您正在更改UI /状态,则会调用ngOnChanges
当与输入绑定的值发生更改时,将调用ngOnChanges() (OnChanges),因此您可以在输入更改时运行自定义代码。
当更改检测运行时,将调用ngDoCheck() (DoCheck),因此您可以实现自定义更改检测操作。
 ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
     console.log('on change', changes)
  }

如果您正在处理HTTP响应并希望观察它,则可以使用BehaviorSubject。请查看以下示例,
调用API的服务 - TestService。
        private test = new BehaviorSubject<any>(null);

        getTest() {
            // ...
            return this.http.get(_url, options)
                .map(response => {
                    const responseAsObject = response.json();
                    this.test.next(responseAsObject); // change the value!
                });
        }

在你的组件中。
        export class TestComponent implements OnInit{
            private testObj : any;

            constructor(
              private testService: TestService,
            ) {}

            ngOnInit() {
                this.testService.getTest
                    .subscribe(test => {
                        // here is the test object from the service, you can do whatever you want with it
                        // it fires when you get the updated response
                });  
            }
        }

希望这可以帮到你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接