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

6
  • You don't seem to be using Angular at all, why did you use the tag ? Commented Mar 19, 2019 at 12:29
  • Sorry the project is built in angular but this specific script isn't, I'll remove it. Commented Mar 19, 2019 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 ? Commented Mar 19, 2019 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? Commented Mar 19, 2019 at 12:40
  • 1
    Possible duplicate of How to use fetch in typescript Commented Mar 19, 2019 at 12:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the answer, where would I put the API url? Sorry im pretty new to typescript.
Where would you put it for what?
The JSON will be requested from an API and I don't see a place to put the JSON url in your example, thanks
@DanielFaulkner you already put it in FaqFakeDb. My code should work with the class you already have
Could you show the example with my code please, I cant seem to get it working, 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.