Angular2 Query Params Subscription Fires Twice

后端 未结 8 1442
闹比i
闹比i 2020-12-25 11:07

Trying to handle an OAuth login scenario where if the user lands on a page with authorization_code in the query string, we process the token and continue

相关标签:
8条回答
  • 2020-12-25 11:59

    Just in case someone is looking for a solution to this, I found a workaround that works pretty well. The solution I came up with involves only doing the subscription on the NavigationEnd event of the Router instance.

    import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      constructor(
        private route: ActivatedRoute,
        private router: Router
      ) {}
      ngOnInit() {
        this.router.events
          .subscribe(e => {
            if (e.constructor.name === 'NavigationEnd' && this.router.navigated) {
              this.route.queryParams
                .subscribe(params => {
                  // do something
                })
                .unsubscribe();
            }
          });
      }
    
    0 讨论(0)
  • 2020-12-25 12:04

    Put your subscription code on ngAfterViewInit method,

    ngAfterViewInit() {
        this.route.queryParams.subscribe(params => {
          debugger;
        });
    }
    
    0 讨论(0)
提交回复
热议问题