How can I utilize Angular 7 to retrieve data from the Wikipedia API and map the results to a custom model?

I've been attempting to connect to the Wikipedia API using Angular 7, but I keep receiving null results.

When I make a call directly to the Wikipedia API site with the following URL: https://en.wikipedia.org/api/rest_v1/page/summary/Addax?redirect=true, I successfully receive a properly formatted JSON response.

However, when I make the same request from my application, the response body is empty.

Below is the code snippet for the HTTP request:

export class WikirestService {
  constructor( private http:  HttpClient) { }

  getWiki(title: string) {
    const tempTitle = title.replace(' ', '_') + '?redirect=true';
    const baseUrl = 'https://en.wikipedia.org/api/rest_v1/page/summary/';
    return this.http.get<WikiSummary>(baseUrl+tempTitle);
  }
}

And here is the structure of the WikiSummary Model:

 export class WikiSummary {
      type?:          string;
      title?:         string;
      displaytitle?:  string;
      namespace?:     Namespace;
      wikibase_item?: string;
      titles?:        Titles;
      pageid?:        number;
      thumbnail?:     Originalimage;
      originalimage?: Originalimage;
      lang?:          string;
      dir?:           string;
      revision?:      string;
      tid?:           string;
      timestamp?:     Date;
      description?:   string;
      content_urls?:  ContentUrls;
      api_urls?:      APIUrls;
      extract?:       string;
      extract_html?:  string;
    }

Despite setting up the model correctly, it always remains null. Even after logging the results, they are still null. Below is how I call the service from the component:

this.wikiRest.getWiki(this.title).subscribe(data => { temp = data; });

I have been struggling with this issue for hours and would greatly appreciate some assistance. This is my first time encountering difficulties while working with an External API.

Answer №1

After implementing the code as suggested, I tested it out and found that it works perfectly fine without any errors. It is possible that you might be attempting to access the value of 'temp' outside of the asynchronous call. The 'data' value can only be accessed within the result block, without requiring any additional steps.

   this.wikiRest.getWiki('Addax').subscribe(data => {
      console.log(data.description);
    }, err => { console.log('Something went wrong: ' + err)
  }); 



getWiki(title: string) {
  const tempTitle = title.replace(' ', '_') + '?redirect=true';
  const baseUrl = 'https://en.wikipedia.org/api/rest_v1/page/summary/';
  return this.http.get<WikiSummary>(baseUrl+tempTitle);
}

export class WikiSummary {
  type?:          string;
  title?:         string;
  displaytitle?:  string;
 // namespace?:     Namespace;
  wikibase_item?: string;
  //titles?:        Titles;
  pageid?:        number;
  //thumbnail?:     Originalimage;
 // originalimage?: Originalimage;
  lang?:          string;
  dir?:           string;
  revision?:      string;
  tid?:           string;
  timestamp?:     Date;
  description?:   string;
  //content_urls?:  ContentUrls;
  //api_urls?:      APIUrls;
  extract?:       string;
  extract_html?:  string;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to enhance an input field: incorporating unique buttons within

Currently, I have an input that is supposed to resemble the following: https://i.sstatic.net/pgPgk.png To achieve this look, I've implemented the code below using Styled-Components and Font-Awesome icons: <Thing> 1 <i className="fa fa ...

Unable to construct the Angular project at this time

I recently downloaded an Angular project that includes an Angular select component from the internet. Here is the original example: https://material.angular.io/components/select/overview#resetting-the-select-value You can check out a demo of this projec ...

Mapping JSON arrays to Angular models using the map operator

I am facing the challenge of mapping JSON array objects from my server to an angular model. I believe that the ideal time to do this is as soon as I receive them in the pipeline at the map function. However, I am unsure about how to accomplish this using t ...

Using Angular to create an Echarts timeline that showcases 3 distinct categories

Here is an example graph created with Highcharts Struggling to replicate a chart like this using Echarts and ngx-echarts. Has anyone encountered this issue before? Currently utilizing the following dependencies: "@angular/animations": "^17 ...

What is the best method for transferring data to Angular routed components?

Within one of my Angular 2 routes templates, specifically in FirstComponent, there is a button present. first.component.html <div class="button" click="routeWithData()">Pass data and navigate</div> The main objective here is to: When the ...

Issue with TypeScript when utilizing the Spread syntax?

https://i.sstatic.net/b9Yz6.png Every time I implement the spread operator like demonstrated below public outputTestData(p1: number, p2: number, p3: number):void { console.log(p1, p2, p3); } let data = [2, 2, 5]; this.outputTestData( ... data ); An e ...

In the api route.ts file, a JSON Response type is returned using axios

Creating an MSA involves utilizing both a front server and backend server. In this case, the frontend calls the api/route structure file api, which then calls the backend api using axios. However, I keep encountering a red line error mark when trying to us ...

No bugs appeared in Next.js

I am currently in the process of migrating a large create-react-app project to NextJS. To do this, I started a new Next project using create-next-app and am transferring all the files over manually. The main part of my page requires client-side rendering f ...

Implementing Google OAuth in Angular 12 utilizing @angular/fire@^7.0.0 and firebase@^9.0.0

After including angular/fire modules in app.module.ts import { provideFirebaseApp, getApp, initializeApp } from '@angular/fire/app'; import { getFirestore, provideFirestore } from '@angular/fire/firestore'; @NgModule({ imports: [ ...

The 'catch' property is not found within the type 'PromiseLike<void>'

Help! I'm encountering a Typescript Error. An issue is arising with the 'catch' property on type 'PromiseLike<void>'. I am using Ionic and facing an error in the line containing catch: sendrequest(req: connreq) { var p ...

Angular refreshes outdated DOM element

Within my Angular (v9) application, I have a simple component. The main goal of this component is to display the current date and time when it is first shown, and then after a 2-second delay, enable a button. Here's the code snippet from app.component ...

Enhancing Angular: Creating a custom HttpInterceptor for handling unique scenarios

In Angular there is the HTTPInterceptor feature called @Injectable() export class HTTPRequestInterceptor implements HttpInterceptor { intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next ...

Animating Page Transitions within Ionic 2

In my Ionic 3 application, I have a basic tabs template where I switch between tabs by swiping left or right. Everything works perfectly except there is no animation effect when transitioning between tabs either by tapping or swiping. I am able to achieve ...

Choose the return type based on the function parameters

I'm currently delving into the world of Graphql and Typescript, trying to specify the data I want returned from a request and communicate those types effectively in my functions. Below is the snippet of code that showcases my current approach: // Th ...

Sending data from one Angular component to another on a button click

I have a background in Python, but I recently started delving into learning Angular and I'm encountering some difficulties. The concept of working between components is proving to be quite confusing for me, and I'm struggling to grasp it. Despite ...

Leveraging es6-promise in conjunction with TypeScript 2.1 and ES5 Webpack for streamlined async/await functionality

Utilizing es6-promise with TypeScript version 2.1.1 that targets ES5 and webpack in my project has presented some challenges. app.ts import "es6-promise/auto"; export class Foo { bar() : Promise<string>{ return Promise.resolve("baz"); ...

Struggling to configure Sass with @snowpack/app-template-react-typescript

I'm struggling to integrate Sass with the @snowpack/app-template-react-typescript template. I attempted to follow the steps outlined in this guide, but so far I haven't been successful. I even created a new project and tried adding it, but not ...

Compatibility between Node JS 6.9 and Angular CLI versions

Having a limitation of using node JS version 6.9.1 has been causing multiple issues for me while attempting to follow the quick start steps with Angular CLI. Upon running ng serve, the browser displays a blank white page without any errors in the console ...

Is it possible to modify the dropdown menu so that it opens on the right side instead of using a select tag?

Is there a way to make the drop-down from the select tag open to the right side(drop-right)? <label for="ExpLabel">Select Message Expiry:</label> <select name="ExpSelect" id="Expiry"> <option value="ExpiryDate">1 Day</opt ...

Retrieval of targeted keywords within a given paragraph using JavaScript

Currently tackling a project in react native (JS based) where I'm tasked with identifying and extracting the names of hospitals from dynamic paragraphs sourced from the backend server. Traditional methods such as match(), includes(), and more aren&apo ...