2
votes

In Ionic application, we are integrating AWS-Amplify and we can able to insert and fetch the data. But while implementing subscription we are getting compiler error says

Property 'subscribe' does not exist on type 'Promise | Observable'. Property 'subscribe' does not exist on type 'Promise'.

In Subscription.ts

export const onCreateEmployee = `subscription OnCreateEmployee(
  $employee_id: Int
  $employee_name: String
) {
  onCreateEmployee(
    employee_id: $employee_id
    employee_name: $employee_name
  ) {
    employee_id
    employee_name
  }
}

In Main.ts

const subscription = API.graphql(
      graphqlOperation(onCreateEmployee)
    ).subscribe((eventData) => { console.log(eventData)
    });

In main.ts, it shows the error like cannot subscribe ..... (see the above error).

Can anybody know how to resolve this?

Thanks

4

4 Answers

0
votes

It's a workaround, but you can convert Observable to Promise

let graphqlCallPromise: Promise<any>;

if(graphqlCall instanceOf Observable) graphqlCallPromise = API.graphql(graphqlOperation(onCreateEmployee)).toPromise();

graphqlCallPromise.then((eventData) => { console.log(eventData) });
0
votes

As the result from API.graphql() can be both, a Promise when you query data for immediate return and alternatively an Observable for subscriptions, you need to tell TypeScript what to expect:

(API.graphql(
  graphqlOperation(onCreateEmployee)
) as unknown as Observable<YourEventDataType>)
.subscribe(
  (eventData) => { console.log(eventData) }
);
0
votes

If this problem occurred specifically when using typescript. you can get around with this by casting it to any

(API.graphql(
      graphqlOperation(onCreateEmployee)
 ) as any).subscribe((eventData) => { console.log(eventData)
 });
-3
votes

probably graphql return a promise instead of observable. Use then to cache the result.

API.graphql(
  graphqlOperation(onCreateEmployee)
).then((eventData) => { console.log(eventData)
});