ActivatedRoute.params.subscribe调用了两次

问题描述

我需要获取URL参数,因此在ngOnInit()中,我有以下部分:

this.activatedRoute.queryParams.subscribe(params => {
    console.log(params);

    // some real code
});

但是,当我访问页面时(例如localhost:8100/?foo=bar&bar=baz),首先获得空对象({}),然后才获得实数值(例如{"foo": "bar","bar": "baz"})。有什么办法摆脱它?

解决方法

在订阅之前添加.pipe(filter()),以确保只有具有实际值的对象才能继续到订阅回调中

this.activatedRoute.queryParams
    .pipe(filter((p: any) => p.foo && p.bar)) //type check the incoming value
    .subscribe(params => {
        console.log(params);

        // some real code
    });