Updating a div dynamically in Angular 2 using data fetched from an http.get request

I have a menu column on the left side and a content section on the right side. Whenever I click on a menu item on the left side, an http.get request is triggered and I receive response data. However, I am unsure how to update the content section with this data. Any help would be greatly appreciated...

Component TS

import {Component} from 'angular2/core';
import {Http} from "angular2/http";
import {HTTPTestService} from "./http-test.service";
import {HTTPSecondComponent} from "./http_second.component";
import {Observable} from 'rxjs/Rx';
@Component({
    selector: 'http-test',
    template: ` <div class="leftside">
      <ul> //left side menu iteration
               <li *ngFor="#item of getData?.items" (click)="getPosts()">  
                        <a href="#">{{item.name}} 
               </a>
               </li>   
      </ul>
            //content to display ======= where i struggle to update data
           <div *ngFor="#data of postData?.datas"> {{data.creation_date}}
            </div>
      </div>
     `,
       directives: [HTTPSecondComponent],
     providers:[HTTPTestService],
      styleUrls:["../src/css/http-style.css"]   
})
export class HTTPTestComponent {
    public getData;
    public postData;
    public displayName;
    public creationDate;
    constructor (private _httpService: HTTPTestService){}
     getStack()
      {
          this._httpService.getItemData()
         .subscribe(             
             data =>this.getData = (data),
                // console.log(this.httpData);},
             error => alert(error),
             () =>console.log("finished")
         );
     }
   getPosts(){

              this._httpService.getPostData()
         .subscribe(             
             data =>this.postData = (data),
                // console.log(this.httpData);},
             error => alert(error),
             () =>console.log("finished")
     );
   }
     ngOnInit() {
    this.getStack();
    this.getPosts();
  }
}

Service TS

import {Injectable} from "angular2/core";
import {Http} from "angular2/http";
import 'rxjs/add/operator/map';
@Injectable()
export class HTTPTestService {
    constructor(private _http: Http) { }
    getItemData(){
        return this._http.get('https://api.stackexchange.com/2.2/sites').map(res => res.json());
    }  
getPostData(){
    return this._http.get('https://api.stackexchange.com/2.2/posts?order=desc&sort=activity&site=stackoverflow').map(res=>res.json());
}
}

Data Received for Content When Menu Link is Clicked

    {
    "datas": [
        {
            "owner": {
                "reputation": 3589,
                "user_id": 1376277,
                "user_type": "registered",
                "accept_rate": 34,
                "profile_image": "https://www.gravatar.com/avatar/195fcc7db00488b207c67ccfee6a2c5b?s=128&d=identicon&r=PG",
                "display_name": "Rahul Gupta",
                "link": "http://stackoverflow.com/users/1376277/rahul-gupta"
            },
            "score": 1,
            "last_edit_date": 1483342788,
            "last_activity_date": 1483342788,
            "creation_date": 1423733190,
            "post_type": "question",
            "post_id": 28473725,
            "link": "http://stackoverflow.com/q/28473725"
        }
    ]
}

Answer №1

If you want to ensure that the ngOnInit function in your class is executed, you need to make sure it is implemented by OnInit. This can be achieved by extending your class as implements OnInit. Update the first line of your class title like so:

export class DataRetrievalComponent implements OnInit {

Don't forget to add OnInit to the imports line as well:

import {Component, OnInit} from 'angular2/core';

By making these changes, your functions getData() and fetchRecords() will be automatically executed when the component starts.

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

The @output decorator in Angular5 enables communication between child and

Hello fellow learners, I am currently diving into the world of Angular and recently stumbled upon the @output decorators in angular. Despite my best efforts to research the topic, I find myself struggling to fully grasp this concept. Here's a snippet ...

Tips for making use of incomplete types

Is there a way to reference a type in TypeScript without including all of its required fields, without creating a new interface or making all fields optional? Consider the following scenario: interface Test { one: string; two: string; } _.findWhe ...

Strange occurrences with HTML image tags

I am facing an issue with my React project where I am using icons inside img tags. The icons appear too big, so I tried adjusting their width, but this is affecting the width of other elements as well. Here are some screenshots to illustrate: The icon wit ...

Tips for handling TypeScript error TS2339 - Property does not found on type

Incorporating Angular 8 (initiated a project in Visual Studio 2019) and currently working with a fabric.init.ts file containing the following content: import 'fabric'; import * as fabric from 'fabric/fabric-impl'; // (TS) Property &ap ...

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

Different ways to handle dialogs in React with TypeScript

I'm currently working on developing a modal component in React TypeScript and I'm facing some issues in determining the correct type for a reference of an HTML dialog element. import { useRef } from 'react' const MyModal: React.FC = () ...

When incorporating FontAwesome 6 into Angular 18, an error might arise stating, "Unable to associate 'spin' as it is not a recognized attribute of 'fa-icon'."

LAST UPDATE: https://github.com/FortAwesome/angular-fontawesome/blob/main/docs/upgrading/0.14.0-0.15.0.md Confirmed not a bug, it's deprecated. UPDATE - I believe it may be a bug. The version of Font Awesome on one machine is 0.14, while the non-wor ...

Is there a way to drop a pin on the Google Maps app?

Is there a way to pinpoint the specific location on Google Maps? <google-map id="map-container" width="100%" height="100%" class="maps"></google-map> ...

Update a particular form field value prior to submission

Currently, I am working on a User registration page that includes the functionality for users to upload their own avatar picture. My approach involves uploading the picture, then calling a function on change to convert the picture into a UInt8Array before ...

Implement a context path in Angular 2 for enhanced functionality

Is there a way to change the base URL for my app from http://localhost:4200 to http://localhost:4200/pilot/? I attempted to modify the base href in index.html, but encountered an Uncaught SyntaxError: Unexpected token < This is the code snippet from m ...

What are the downsides of utilizing a global function over a private static method in Typescript?

It's quite frustrating to have to write this.myMethod() or ClassName.myMethod() instead of just myMethod(). Especially when dealing with a stateless utility function that doesn't need direct access to fields. Take a look at this example: functi ...

Tips for utilizing method overload in TypeScript with a basic object?

Looking at this code snippet: type Foo = { func(a: string): void; func(b: number, a: string): void; } const f: Foo = { func(b, a) { // ??? } } An error is encountered stating: Type '(b: number, a: string) => void' is not assign ...

Illuminating JavaScript code with the help of ngx-prism

Looking to enhance the readability of code on my website, I decided to incorporate syntax highlighting. After some research, I came across ngx-prism. Following the steps outlined in its documentation: I executed the following commands: npm i --save @n ...

The Angular MatStepper is unable to detect saved values from two string arrays, although it is able to detect values from a different string array

In my application, there is a MatStepper component that facilitates navigation through the signup flow. A method exists to load cached values when available, causing the MatStepper to skip to Page 2. Subsequently, another method pre-fills the form with the ...

Utilize Angular 9 to fetch data from an API using the Get method, map them to a class, and

Seeking to extract information from a test URL and convert the data into a list, I aim to exhibit them in an alert/Loop for testing purposes. The dummy API URL being used is: The returned data follows this structure: {"status":"success","data":[{"id":"1" ...

Creating hierarchical TreeNode structure in TypeScript

As I work with a flat one-dimensional array of type TreeNode (view interface definition below), my goal is to recursively traverse the array and add subsequent array elements as children. While attempting a non-recursive approach using a buffer, I encount ...

Issue encountered when attempting to import a module within the ionic framework

I encountered an issue in my project (built with the ionic-framework 3) where I included the following line to import the dialogflow module: const dialogflow = require('dialogflow'); However, when compiling, it resulted in the error message: ...

When a React Native TextInput is focused, it restricts the ability to press other child components

Issue with Nested TextInput component affecting onPress function of other components. Press only works when the TextInput is not in focus. React Native Version : 0.66.3 Here's the code snippet: export const Component = (props): JSX.Element { const ...

Issue with ngStyle function in Internet Explorer

Within my Angular 4 application, I have defined styles as shown below: [ngStyle]="{'border': getInterleaveColor(i)}" The following function is also included: getInterleaveColor(auditNumber) { var borderProperties = '2px solid'; ...

Solutions for Utilizing Generic Mixins in Typescript

As a newcomer to Typescript, I have encountered an issue with mixins and generics. The problem became apparent when working on the following example: (Edit: I have incorporated Titian's answer into approach 2 and included setValue() to better showcas ...