0

I want the code below to be able to fetch JSON data from a simple API I have set up.

export class FaqFakeDb
{ 
    public static data = fetch('https://#######.co.uk/api/faq/');
}

This is for a FAQ page and its meant to be pulling data from the API. I am new to typescript and Angular so forgive me if I've made a simple mistake.

I want it to function like this:

export class FaqFakeDb
{
    public static data = [  
        {  
           "id":"1",
           "question":"test1",
           "answer":"test1"
        },
        {  
           "id":"2",
           "question":"test1",
           "answer":"test1"
        },
        {  
           "id":"3",
           "question":"test1",
           "answer":"test1"
        }
     ];
  }

Any help will me much appretiated :)

  • You don't seem to be using Angular at all, why did you use the tag ? –  Mar 19 '19 at 12:29
  • Sorry the project is built in angular but this specific script isn't, I'll remove it. – Daniel Faulkner Mar 19 '19 at 12:34
  • 1
    Well if you use Angular in your project, why don't use you their HTTP module instead of the fetch API ? –  Mar 19 '19 at 12:37
  • TypeScript is more familiar to me than Angular and this is how the template is set up so I'm just trying to get it working this way for now, Do you know what I did wrong? – Daniel Faulkner Mar 19 '19 at 12:40
  • No sorry, I haven't used the fetch API yet, let alone with Typescript ... But good luck with your issue though :) –  Mar 19 '19 at 12:44
  • 1
    Possible duplicate of [How to use fetch in typescript](https://stackoverflow.com/questions/41103360/how-to-use-fetch-in-typescript) – Nikola Lukic Mar 19 '19 at 12:47

1 Answers1

1

fetch returns a promise, so data will be a promise. Any time you want to access data you will have to use async/await or .then or something else to handle promises. You also don't have any error handling in case your API call fails.

One example of how you could handle this would be:

async ngOnInit() {
  try {
    const response = await FaqFakeDb.data;
    this.quesitons = await response.json();
  } catch {
    // fetch encountered an error; you can handle it here.
  }
}

However, I would recommend that you use Angular's built in HttpClientModule instead and make the API call as it's needed (in the component that needs it) rather than when an arbitrary class is declared.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405