I'm using the JSONPlaceholder API: https://jsonplaceholder.typicode.com. I have the following in my service.ts:
public async getPosts(): Promise<Post[]> {
try {
const response = await this._http.get<Post[]>(this._baseUrl + "api/JsonPlaceholder/GetPosts");
return response.toPromise();
} catch (error) {
await this.handleError(error);
}
}
Which I try to use in my component.ts:
public posts: Post[];
public async ngOnInit() {
const posts = await this._placeholderService.getPosts();
this.posts = posts;
}
However, the TypeScript compiler throws an error on public async getPosts(): Promise<Post[]> - Function lacks ending return statement and return type does not include 'undefined'.
It is expecting a return statement in either the catch block or outside the try-catch. What is best practice for handling errors like this when I want to return a specific type...in my case Post[]. Is there a better way to structure these types of calls?