Skip to content

Commit

Permalink
feat: Tratamento de erro quando 401
Browse files Browse the repository at this point in the history
  • Loading branch information
wallanpsantos committed Dec 7, 2023
1 parent d3bb5b6 commit ebc9b24
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 21 deletions.
13 changes: 11 additions & 2 deletions src/app/auth-content/auth-content.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,19 @@ export class AuthContentComponent {
ngOnInit(): void {
this.axiosService.request(
"GET",
"/v1/informations",
"/v1/messages",
{}
).then(
(response) => this.data = response.data
(response) => {
this.data = response.data;
}).catch(
(error) => {
if (error.response.status === 401) {
this.axiosService.setAuthToken(null)
} else {
this.data = error.response.code
}
}
)
}
}
35 changes: 16 additions & 19 deletions src/app/axios.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,32 @@ import axios from "axios";
})
export class AxiosService {

private readonly AUTH_TOKEN_KEY = 'auth_token';
private readonly AUTH_TOKEN_KEY = "auth_token";

constructor() {
axios.defaults.baseURL = 'http://localhost:8080';
axios.defaults.headers.post['Content-Type'] = 'application/json';
}

request(method: string, url: string, data: any): Promise<any> {
/* Gerenciar o acesso ao armazenamento local */
getAuthToken(): string | null {
return window.localStorage.getItem(this.AUTH_TOKEN_KEY)
}

let headers = {}
setAuthToken(token: string | null): void {
if (token !== null) {
window.localStorage.setItem(this.AUTH_TOKEN_KEY, token)
} else {
window.localStorage.removeItem(this.AUTH_TOKEN_KEY)
}
}

const authToken = this.getAuthToken();
request(method: string, url: string, data: any): Promise<any> {
let headers = {}

/* Cabeçalho de autorização caso token estiver presente em localstorage */
if (authToken !== null) {
headers = {"Authorization": `Bearer ${authToken}`}
if (this.getAuthToken() !== null) {
headers = {"Authorization": "Bearer " + this.getAuthToken()};
}

return axios({
Expand All @@ -31,17 +41,4 @@ export class AxiosService {
headers: headers
})
}

/* Gerenciar o acesso ao armazenamento local */
getAuthToken(): string | null {
return window.localStorage.getItem(this.AUTH_TOKEN_KEY)
}

setAuthToken(token: string | null): void {
if (token !== null) {
window.localStorage.setItem(this.AUTH_TOKEN_KEY, token)
} else {
window.localStorage.removeItem(this.AUTH_TOKEN_KEY)
}
}
}

0 comments on commit ebc9b24

Please sign in to comment.