How to effectively send an HTTP GET request to a REST API in Angular 2 and save the response in a JSON object

Currently, I am attempting to execute a GET request to the GitHub API using Angular2. The returned data is in JSON format, and my goal is to store it in a JSON object for further processing.

While referring to the Angular2 documentation for guidance, I encountered the following code snippet:

getHeroes (): Observable<Hero[]> {
  return this.http.get(this.heroesUrl)
                  .map(this.extractData)
                  .catch(this.handleError);

However, I faced a challenge around defining the 'Hero[]' variable for the API, especially since it doesn't align with the specific structure outlined in the documentation (which includes 'id' and 'name' attributes). Therefore, I am seeking assistance in creating an Observable function that can retrieve and store the data in an object format.

In a previous Angular 1.5 project, I implemented a similar functionality as shown below:

var urlBase = 'https://api.github.com/search/repositories?q=';
    var SearchOp = {};
    SearchOp.getRepositories = function (search) {
        SearchOp = $http.get(urlBase+ search +'&sort=star&order=desc&per_page=5')
        return SearchOp;
    };

In my current Angular2 implementation, I have structured my code like this:

 search (term: string) {

    let gitUrl = 'https://api.github.com/search/repositories';
    let params = new URLSearchParams();
    params.set('q', term); 

    let result = this.http
               .get(gitUrl, { search: params })
               .map(request => request.json());
               console.log(result);
               return result;
  }

However, the output displayed in the console is:

'Observable {_isScalar: false, source: Observable, operator: MapOperator}'

Which isn't the expected result I was hoping for.

Answer №1

When making a call using http.get(), it is important to note that the call is asynchronous. This means that the function request => request.json is a callback function added to map(...) that will be executed when the response from the server is received. The HTTP call is placed in the event queue of the browser for processing at a later time, allowing the code in your search method to continue running immediately.

As a result, the console.log(result) statement will be executed before the request is actually sent to the server.

If you want certain code to run only after the data has been received, it should be placed inside the map(...) function.

return this.http
           .get(gitUrl, { search: params })
           .map(request => {
             request.json()
             console.log(result);
             // return result; // this method does not work as expected
           });

It is also important to note that you cannot simply return the result directly because the result may not be available once the function completes execution.

In the provided code snippet, the result is assigned an Observable which allows it to be subscribed to for future updates.

For instance, the following line sets the response data to this.data once it is received:

this.search(term).subscribe(data => this.data = data);

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

Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below ...

What is the method to access the value of a different model in ExpressJs?

I am working on a MEAN stack and have a model for employee information. I want to include the store name where they will work from a separate stores model. Can you review my approach below? Employee Model: var mongoose = require('mongoose'); va ...

Retrieving Data from API in Angular 6/7 upon Navigating Back to Previously Visited Page

I'm currently navigating my way through angular and encountering a small hurdle. I aim to guide a user to a data entry page where most fields are pre-filled by retrieving data from the database based on a record id. The user then modifies some fields, ...

Manipulating data in Angular using RxJs - Creating, Reading,

public ngOnInit() { this.fetchUsers(); } public fetchUsers() { this.userService.getUsers(this.listId).pipe(take(1)).subscribe(data => { if (data.result.length) { this.users = data.result; } else { const user = new UserModel(); ...

Having trouble with installing the angular-4-data-table-bootstrap-4 package in NG 4.4.6 environment

I am currently working on an NG 4 project and my package.json indicates that I am using angular 4.4.6. I am attempting to include the angular-4-data-table-bootstrap-4 package as outlined below, but I keep encountering the error mentioned here that I can&ap ...

Using spyOn to fake Observable responses - a step-by-step guide

My service is set up to request JSON data through HTTP: export class TodosService { constructor(private http: HttpClient) {} getTodos(): Observable<any> { return this.http.get<any>('https://jsonplaceholder.typicode.com/todos') ...

Unable to retrieve the reflective metadata of the current class instance

Is it possible to retrieve the reflect-metadata from an instance of a class? The documentation provides examples that suggest it should be achievable, but when I attempt to do so, I receive undefined as a result. Strangely enough, when I request the metada ...

Creating an interface in Dart: Step-by-step guide to defining interfaces similar to TypeScript

Coming from a Typescript background, I used to define object interfaces like this: export interface Locale { login: { title: string; actions: { submit: string; forgot: string; } } } However, in Dart, interfaces are implicit an ...

Can you please verify the most recent updates for Bootstrap and Syncfusion in my Angular project?

Could someone help me figure out when the bootstrap and syncfusion libraries were last updated in my Angular project? I'm having difficulty finding this information. ...

A better choice than Java's <? super SomeType> in Typescript

Is there a scenario in which one of the generic parameters used to create an instance of my class should be a superclass of another class? In Java, this is easily achievable using <? super SomeType>. What would be the equivalent in TypeScript? ...

The error at core.js:4002 is a NullInjectorError with a StaticInjectorError in AppModule when trying to inject FilterService into Table

While exploring PrimeNg Table control in my application - as a beginner in PrimeNg & Angular, I encountered an error No provider for FilterService! shown below: core.js:4002 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppMo ...

Creating Instances of Variables Within a Class

Currently, I am working on a project using Ionic and Angular. I have come across various ways of instantiating variables and I'm unsure about the implications of each method. Here are three scenarios that confuse me: export class someClass { myVaria ...

Develop an Angular 6 application that utilizes an observable to monitor changes in a variable

I am working with Angular 6 and I need to monitor a variable for any changes and then stop or unsubscribe when the variable has a value. My initial thought was to use an Observable: myValue; // The variable that needs to be monitored myObservable = Obse ...

Compelled to utilize unfamiliar types in TypeScript generics

When working with a Typescript React form builder, I encountered a situation where each component had different types for the value and onChange properties. To tackle this issue, I decided to utilize generics so that I could define the expected types for e ...

Angular: Retain the original value of the observable

When making HTTP requests to a backend and receiving data, I use an observable stream and subscribe to it in my HTML template using async pipe. However, I am facing an issue. I need to continuously send multiple requests by clicking a button, but I want th ...

How can one retrieve videos from a YouTube channel using Angular 2 within the Ionic 2 Framework?

Can someone help me understand how to fetch and display videos in my Angular 2 Android App using Ionic 2? I am new to both technologies. .component.js File export class HomePage implements OnInit { private videoListArr = []; private title = []; privat ...

What is the reason behind the sudden red coloring of parentheses in Visual Studio Code while typing in TypeScript?

Previously, their color was white as showcased on https://code.visualstudio.com/docs/languages/typescript. https://i.sstatic.net/CbzqE.png ...

What causes the error message saying 'undefined' cannot be assigned to the specified type ...?

I just finished developing an innovative Angular application. Within the app.component.html file, I have included: <bryntum-scheduler #scheduler [resources] = "resources" [events] = "events" [columns] = "schedul ...

Angular: Exploring the Dynamic Loading of a Component from a String Declaration

Is there a way to compile a component defined by a string and have it render in a template while still being able to bind the click event handler? I attempted to use DomSanitizer: this.sanitizer.bypassSecurityTrustHtml(parsedLinksString); However, this a ...

After triggered window.print() in Angular, the window:afterprint event is failing to work as

I am triggering window.print() with a button click <button class="btn btn-primary" type="button" (click)="printDocument()"> Print </button> Inside the printDocument method, I open the document in a new window and ...