I
I
Innokenty Ivanov2019-01-27 10:17:14
Angular
Innokenty Ivanov, 2019-01-27 10:17:14

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));
    });
  }

There is code in the component that calls this function:
room-list.component
export class RoomListComponent {
  constructor() {

    this.rooms = async () => { await this.roomService.getAll(); };

  }
}

We write a fairly simple error about type incompatibility:
error TS2740: Type '() => Promise<void>' is missing the following properties from type 'Room[]': pop, push, concat, join, and 25 more

How to solve this problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
msdosx86, 2019-01-27
@msdosx86

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

D
Demian Smith, 2019-01-27
@search

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))
}

Is it easier too?
C axios never worked, so this answer might be full of crap. But try the suggestion. Judging by the description of the types , everything should turn out as expected.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question