0

I am really new to angular, and wanted to understand how can i call async on Oninit. I have one service which is using asyn/await. i want to be able to use this in OnInit. however, I am not able to use it. because before service call is complete code executes to next line and it throws ZoneawarePromise error.

My Service method looks like below

 public async getProjects():Promise<Observable<any>>{
    const querySpec = {query: "SELECT * from c"};
    const { resources:items } = await this.container.items.query(querySpec).fetchAll();
    return of(items);
  }

and this is how i am trying to call it within ngOnInit

async ngOnInit(){
      (await this.projectData.getProjects()).subscribe(data=>{
   
       //All the other code goes here, basically creating a HTML content

what could be the right way to call a service ?

1
  • Why are you turning your promise into an observable? return of(items);. getProjects should just return an Observable or a promise not both Commented Aug 17, 2020 at 15:09

1 Answer 1

1

your problem is Promise of Observable,

 public async getProjects():Promise<Array<any>>{
    const querySpec = {query: "SELECT * from c"};
    const { resources:items } = await this.container.items.query(querySpec).fetchAll();
    return items;
  }

then

async ngOnInit(){
      const data = await this.projectData.getProjects();
      console.log('data',data);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply, Now, I am getting ERROR TypeError: Cannot read property 'toArray' of undefined.
I figured the issue. It was mainly because of not initialising the variables properly. once i did it. its working fine. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.