I'm using a service for making all webrequest like that:
@Injectable({
providedIn: 'root'
})
export class WebService {
auth_token: string;
constructor(public config: ConfigService, public http: HttpClient, public router: Router) {
// load token
this.auth_token = localStorage.getItem("token") ? localStorage.getItem("token") as string : "";
}
public async get<T>(dir: string) {
return await this.http.get<T>(this.config.config.backend.url dir, { headers: { 'Authorization': `Bearer ${this.auth_token}`, 'Content-Type': 'charset=UTF-8' } }).toPromise();
}
}
Then, in component, I'm doing like:
constructor(web: WebService) {
web.get<MyObject[]>("obj").then(values => {
for(let obj of values) {
obj.doSomething();
}
});
}
I want to manage error more globally, to don't have to duplicate code. It's mostly to prevent wrong token/expired token/etc.
So, I edited my service to have like this:
public async get<T>(dir: string) {
return await this.http.get<T>(this.config.config.backend.url dir, { headers: { 'Authorization': `Bearer ${this.auth_token}`, 'Content-Type': 'charset=UTF-8' } }).toPromise().catch(err => {
// here manage all err status code
});
}
But the catch
method return Promise<void | T>
and not Promise<T>
. So, I have error on the then()
method because the values
variable can be void. Exact error is: Type 'void | MyObject[]' is not assignable to type 'MyObject[]'.
How can I fix it ?
CodePudding user response:
Return a value in the catch. That can be an empty array for example, when getting a list.
.catch(err => {
// here manage all err status code
return [];
}
However, you need to define beforehand in that case, if the default value for the Promise is an empty array, an empty string, zero or whatever