简体   繁体   中英

ActivatedRoute paramMap observable emits the value twice / firing twice - Angular 4

I'm having a problem with Angular 2/4 and getting a param(s) for the specific route. I did this like hundred times and never had problem like this, as you can see from the code I call paramMap on the route expecting it will be only run once, but somehow it ends up being invoked twice.

It's like paramMap observable is emitting the same value two times instead of one. Problem is that this way I'm making two requests to my server sending duplicate data.

export class UserComponent implements OnInit {
    user: User;
    submitted: Observable<Topic[]>;

    constructor(
        private router: Router,
        private route: ActivatedRoute,
        private service: UserService,
        private topicService: TopicService
    ) {}

    ngOnInit(): void {        
        this.route.data
            .subscribe(res =>  this.user = res.user); 
        // Error is handled by resolver

        this.submitted = this.route.paramMap
            .switchMap((params: ParamMap) => {
               // THIS ONE IS INVOKED TWICE WITH SAME PARAMS
               return this.topicService
                  .getUserSubmitted(params.get("name"));
            });
    }
    .
    .
    .
}

I fetch the user using resolver, at the same time I fetch data (topics) depending on route param (:name) and that's actually it, nothing more.

Okay, I've found the solution so I'll put it here.

Problem is that having session|async with two elements in my template I basically subscribe twice to the same observable (at the time of template initialization).

<div *ngFor="let submit of submitted|async" class="submits">...</div>

<!-- and one more  --> 

<em *ngIf="!(submitted|async)?.length">
     Nothing to show. User has not submitted any topics.
</em>

Angular.io documentation:

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

Source:

Angular - AsyncPipe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM