Angular2 Query Params Subscription Fires Twice

后端 未结 8 1487
闹比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:56

    The best way to overcome this was subscribing router events, and processing query params only after the route is ticked to navigated state:

      public doSomethingWithQueryParams(): Observable {
          let observer: Observer;
          const observable = new Observable(obs => observer = obs);
    
          this.router.events.subscribe(evt => {
            // this is an injected Router instance
            if (this.router.navigated) {
              Observable.from(this.activatedRoute.queryParams)
                // some more processing here
                .subscribe(json => {
                  observer.next(json);
                  observer.complete();
                });
            }
          });
          return observable;
      }
    

提交回复
热议问题