Answer the question
In order to leave comments, you need to log in
Typescript/Angular: What's wrong with returning the result of an async function?
There is this code in the service:
roomService()
public async getAll(): Promise<Room[]> {
const rooms: Room[] = [];
await axios.get('somepath/kek:1488?SeigHeil&joking=true')
.then((response) => {
rooms.push(response.data);
});
return new Promise<Room[]>((resolve, reject) => {
resolve(rooms);
reject((err) => console.log(err));
});
})
.catch((error) => {
console.log(error);
});
return new Promise<Room[]>((resolve, reject) => {
resolve(rooms);
reject((err) => console.log(err));
});
}
export class RoomListComponent {
constructor() {
this.rooms = async () => { await this.roomService.getAll(); };
}
}
error TS2740: Type '() => Promise<void>' is missing the following properties from type 'Room[]': pop, push, concat, join, and 25 more
Answer the question
In order to leave comments, you need to log in
In service
constructor (private http: HttpClient) {}
public getAll() {
return this.http.get('url').pipe(map(res => res.data));
In the component
this.roomService.getAll().subscribe(data => this.rooms = data) Sorry
, I'm writing from my phone
Like if you do
, then the typescript will stop showing off. Because it will explicitly indicate what type of data is returned by the server.
But just the whole getAll() can be made simpler:
public getAll(): Promise<Room[]> {
return axios.get<Room[]>('somepath/kek:1488?SeigHeil&joking=true')
.then(response => response.data)
.catch(err => console.log(err))
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question