[英]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.我正在从后端获取数据并将其显示在 mat 表中,该表在延迟加载模块内的组件上呈现。 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).
一切似乎都工作正常,直到我从浏览器刷新页面(或者它在 ng serve 运行并且我正在编码时自行刷新,顺便说一句,这就是我发现错误的方式)。
On refreshing the page the data fetched from the API no longer shows.刷新页面时,从 API 获取的数据不再显示。 It works when navigating from a different page.
它在从不同页面导航时起作用。
I am using Django rest framework at the backend to serve API to angular client.我在后端使用 Django rest 框架为 API 提供给 ZD18B8624A0F5F721DADD7B82 客户端。 My app authenticates the user in the backend using JWT and in the frontend uses firebase.
我的应用在后端使用 JWT 对用户进行身份验证,在前端使用 firebase。
I am using Http interceptors to add the JWT token to all the Http request.我正在使用 Http 拦截器将 JWT 令牌添加到所有 Http 请求中。
auth.service.ts to get token auth.service.ts 获取令牌
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 api.service.ts 发送 http 请求
public getEmployees(): Observable<Employee[]> {
return this.http.get<Employee[]>(`${this.url}/employee/`);
}
token-interceptor.service.ts for adding the token token-interceptor.service.ts 用于添加令牌
@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.在 Chrome 浏览器开发工具的网络选项卡上,我可以看到在正常导航中获取了 employee/,但是当刷新浏览器时,employee/ 不再存在。
The problem was with the following line: this.afAuth.auth.currentUser.getIdToken()问题出在以下行:this.afAuth.auth.currentUser.getIdToken()
currenUser can be null and we need to afAuth.authState currenUser 可以是 null 我们需要 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? 如何在 angular firebase 中修复“TypeError: Cannot read property 'getIdToken' of null”?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.