简体   繁体   中英

On angular 8 refreshing a page doesn't show the data from backend api

I am fetching data from backend and showing it in a mat table, this table is rendered on a component inside a lazy loaded module. Everything seems to work fine until I refresh the page from the browser ( or it gets refreshed on its own while ng serve is running and I am coding, this was how I found the bug by the way).

On refreshing the page the data fetched from the API no longer shows. It works when navigating from a different page.

I am using Django rest framework at the backend to serve API to angular client. My app authenticates the user in the backend using JWT and in the frontend uses firebase.

I am using Http interceptors to add the JWT token to all the Http request.

auth.service.ts to get token

getToken() {
   let tokenPromise = new Promise ((resolve, reject) => {
    this.afAuth.auth.onAuthStateChanged( user => {

      if (user) {

        this.afAuth.auth.currentUser.getIdToken()
         .then(token => {
           this.userToken = token;
         });
      }

      if (this.userToken) {
        resolve(this.userToken);
      }

    });
   });

   return tokenPromise;

  }

api.service.ts to send http request

public getEmployees(): Observable<Employee[]> {
    return this.http.get<Employee[]>(`${this.url}/employee/`);
  }

token-interceptor.service.ts for adding the token

@Injectable({
  providedIn: 'root'
})
export class TokenInterceptorService implements HttpInterceptor {


  constructor(private authService: AuthService) { }

  intercept(req, next): Observable<any> {

    return from(this.authService.getToken()).pipe(
      switchMap(token => {
          const headers = req.headers
              .set('Authorization', 'JWT ' + token)
              .append('Content-Type', 'application/json');
          const reqClone = req.clone({
              headers
          });
          return next.handle(reqClone);
      }));
 }
}

On Chrome browser developer tool's network tab I can see that employee/ is fetched on normal navigation but when the browser is refreshed, employee/ is no longer there.

The problem was with the following line: this.afAuth.auth.currentUser.getIdToken()

currenUser can be null and we need to afAuth.authState

The detailed answer can be found on the following link:

How to fix "TypeError: Cannot read property 'getIdToken' of null" on browser refresh, in angular firebase?

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