TypeError: You provided 'undefined' where a stream was expected

前端 未结 10 819
广开言路
广开言路 2021-01-11 09:42

I have an Ionic app that has a user provider with a signup() method:

doSignup() {
  // set         


        
10条回答
  •  醉话见心
    2021-01-11 10:22

    I was using ngrx with Angular to store the token. I faced this error in my interceptor.ts.

    The wrong code was this:

    intercept(req: HttpRequest, next: HttpHandler): Observable> {
    
            this._store
                .pipe(
                    select(fromSelectors.selectAuth),
                )
                .subscribe((state: fromReducers.AuthState) => {
    
                    if (state.token != null) {
                        const clonedReq = req.clone({
                            headers: req.headers.set('Authorization', 'Bearer ' + state.token)
                        });
                        return next.handle(clonedReq);
                    }
                    else {
                        this.router.navigate(['login']);
                    }
                });
        }
    

    I fixed the code by returning the flow:

     intercept(req: HttpRequest, next: HttpHandler): Observable> {
    
            return this._store
                .pipe(
                    select(fromSelectors.selectAuth),
                    switchMap((state: fromReducers.AuthState) => {
    
                        if (state.token != null) {
                            const clonedReq = req.clone({
                                headers: req.headers.set('Authorization', 'Bearer ' + state.token)
                            });
                            return next.handle(clonedReq);
                        }
                        else {
                            this.router.navigate(['login']);
                            // return EMPTY stream
                            return of({}) as Observable>;
                        }
                    })
                );
    
        }
    

提交回复
热议问题