What is the process for sending an http get request that provides a JSON array to populate an ngFor directive?

I'm trying to figure out how to make an http get request in order to retrieve a json array of data that I can use within an ngFor loop. The list that needs to be looped through is stored in this.list. Currently, the json file for testing purposes is located on my local machine. Despite looking through Angular 2 documentation and taking a udemy course, I am still struggling with this task. I have a feeling that the solution is simpler than I think.

This is the component containing the ngFor directive:

constructor(private router:Router, private rec:RecommendationsService ){}
      ngOnInit(){
        this.rec.getRecommendations().subscribe(
          data=>{
            this.x = JSON.stringify(data);
            alert(this.x);
            this.list = this.x;
          }
        );
      }

The http get request is handled within a service:

import 'rxjs/Rx';

@Injectable()
export class RecommendationsService{

  url="//Users/Daniel/Desktop/Reccomendations.json";

  constructor(private http:Http){};

  getRecommendations(){
    return this.http.get(this.url).map(res => res.json);
  }
}

Below is the ngfor code snippet where the data is needed:

 <div *ngFor="let item of list, let i = index" data-toggle="modal" data-target="#recModal">
                <div class="row rowTopBuffer rowDiv" (click)="toModal(item.name, item.description, item.recLocLat, item.recLocLong, item.picturePath)">
                    <div class="col-sm-12 col-md-4 titleDiv" >
                        <img class="recommendationImages img-responsive img-rounded" src={{item.picturePath}}>
                    </div>
                    <div class="col-sm-12 col-md-6 descDiv">

                    <p class="itemTitle">{{item.name}}</p>
                    <p id="{{desc+i}}">{{item.description}}</p>

                    </div>
                </div>
            </div>

Currently, when running this code, an EXCEPTION: [object Object] error is displayed in the console.

Answer №1

Avoid converting the object to a string repeatedly, as you cannot iterate through a string :)

ngOnInit(){
    this.rec.getRecommendations().subscribe(
        data => {
            this.x = JSON.stringify(data);
            alert(this.x);
            this.list = data;
        },
        error => console.log(error),
        () => console.log("done")
    );
}

Additionally, remember to call the 'json()' method in your service like this:

getRecommendations(){
    return this.http.get(this.url).map(res => res.json());
}

Furthermore, make sure to correctly use ngFor in your template. Use ; instead of , when specifying the index.

*ngFor="let item of list; let i = index"

Answer №2

Through my extended experience with Angular, I have gained valuable insights and wish to contribute an answer to this query. One option is to return the interface itself, while another is to return a class that incorporates the interface. Angular simplifies the deserialization process.

*************HTML

<div *ngFor="let employee of employees; let i = index;">
  <div>employee.Name</div>
  <div>employee.Id</div>
</div>

*************Typescript class and interface

export interface Employee{
  Id:number;
  Name:string;
}

export class ResponseEmployee implements Employee{
  Id:number;
  Name:string;
}

*************** Http service

@Injectable()
export class EmployeeHttpService {


  constructor(private http: Http) {}

  getEmployees(city:string){

    var headers = new Headers();
    headers.append("Content-Type", "application/json");

    var url = “/api/endpoint/path”;

    return this.http
      .get(url, {headers:headers})
      .toPromise()
      .then((res)=> res.json() as ResponseEmployee[]);

  }

}

**************** Component that uses employeeHttpService

@Component({
  selector: 'display-recommendations',
  templateUrl: './display-recommendations.component.html',
  styleUrls: ['./display-recommendations.component.sass']
})
export class DisplayEmployees implements OnInit {

  employees:ResponseEmployee[]=[];

  constructor(private employeeHttp:EmployeeHttpService){}

  ngOnInit() {

    this.employeeHttp.getEmployees()
      .then((data: ResponseEmployee[])=> {
        this.employees = data;
      })
      .catch((e:Error)=> this.handleError(e));
  }



}

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

Introducing an extra 'pipe' in rxjs angular may result in generating errors

Encountering an unusual issue with Angular. The following code functions correctly: this.form.valueChanges .pipe( startWith(this.form.value), pairwise(), tap(() => console.log('aa')) ...

Creating an external link in Angular with query parameters

I have created an app where users have their addresses listed, and I want to implement a feature that allows me to open Google Maps when clicking on the address. However, I am currently facing an issue where instead of getting the actual value of {{ this. ...

Redirect the user to the shop page in Angular 2 if they already have

How can I set up a redirect for the User ID (this.authTokenService.currentUserData.id) if they are the owner of a shop? owner_id: number; private sub: any; ngOnInit() { this.sub = this.httpService.getShops().subscribe(params => { ...

Navigating in Angular 2.0.0-rc1 with routes and setting a default route using use

Is it true that "useAsDefault" has been removed in angular2.0.0-rc1? Any suggestions for a workaround? I noticed in the Angular documentation they are using the OnInit method... Do subroutes still function with the /... notation? Thanks ...

Is it possible to begin the vue root instance by using a .vue class component?

Utilizing vue-class-component allows me to incorporate class syntax and TypeScript type checking within my .vue files. I can easily create .vue files and register them as components using this method, with the exception of the root Vue() instance. This ap ...

Tips for effectively handling the data received from a webservice when logging into a system

My web service provides me with permissions from my user. The permissions are stored as an array in JSON format. I need to find a way to access and display this data in another function. {"StatusCode":0,"StatusMessage":"Authenticated Successfully", "Token ...

Display a button only when hovering over it

Seeking assistance for a simple task that is eluding me at the moment. I am currently using scss and trying to make a button only appear when hovered over. The button is hidden in the code snippet below, nested within a block alongside some svgs. Any hel ...

The revalidateTag and revalidatePath features in Next.js are currently not functioning as expected

I attempted to utilize the revalidateTag and revalidatePath functions with Next.js version 14.2.3. The objective was: there is a server action to fetch a list of items. also, there is a server action to add an item. upon successful addition of an item, I ...

Using Typescript in NextJS 13 application router, implement asynchronous fetching with async/await

Recently, I implemented a fetch feature using TypeScript for my NextJS 13 project. As I am still getting familiar with TypeScript, I wanted to double-check if my approach is correct and if there are any potential oversights. Here is the code snippet from ...

Ways to pass styling properties to a nested component

I am working on a component that includes an input field: <mat-form-field appearance="standard"> <mat-label >{{label}}<span>*</span></mat-label> <input [type]="type" <span matSuffix>{{suffix} ...

Is it possible to set up TypeScript npm packages to be installed in their original TypeScript format rather than JavaScript for the purpose of examining the source code?

Despite my lack of expertise in the inner workings of how a TypeScript library compiles itself to JavaScript before being placed in the node_modules directory, I have a question: Coming from a PHP background, I am accustomed to being able to explore any l ...

Disabling child FormControl in valueChanges is overlooked when enabling parent form

I have a unique situation with two checkboxes that are connected - one is only enabled if the other is checked. The solution I came up with involves utilizing valueChanges on the first checkbox to control the functionality of the second checkbox dynamical ...

When a user clicks on the download link, it redirects them to the homepage in Angular

When using Angular 6 and the downloadFile method to download an Excel sheet from the WebAPI, everything runs smoothly. A dialog box opens up asking to save the file on the drive, but then it unexpectedly navigates me back to the home page. This redirects ...

What steps are involved in implementing ts-transformer-keys in a Next.js project?

I am trying to extract keys from an interface as a string array so that I can iterate over them. After doing some research on stackoverflow, I found out that I need to use a library called 'ts-transformer-keys'. In my Next.js project, which invol ...

Invoke a function in Playwright exclusively when the test title includes a specific @tag

After years of utilizing Selenium, SpecFlow, NUnit, and other testing tools, I have recently delved into Playwright with TS. My goal is to interact with the AzureDevOps API to mark tests as automated only if they contain a specific tag in the test title (e ...

Creating a HMAC-SHA-256 signature in JavaScript for datatrans: A step-by-step guide

I'm currently working on an Angular project that involves implementing the Datatrans payment system. Unfortunately, I have been facing difficulties in generating a sign for the payment. I have been following the process outlined in this link (enter l ...

Tests in Angular2 are executed before the variables in compileComponents are initialized

I'm encountering an issue with an Angular2 text component where I receive the following error message when trying to run the testrunner: Component: Product Component Should ensure component subscribes to service EventEmitter on instantiation Failed: ...

Does a <Navigate> exist in the react-router-dom library?

Within the parent component import LoginPage from "pages/admin"; export function Home() { return <LoginPage />; } Inside the child component import { useRouter } from "next/router"; export default function LoginPage() { co ...

Experiencing difficulties while attempting to install the Angular-cli tool and encountering errors

Following recommendations, I executed "npm install -g angular-cli" to install the CLI tool. I have successfully installed Windows tools using "npm install --global --production windows-build-tools" and also "npm install -g node-gyp" via PowerShell running ...

The data type 'Observable<any>' cannot be assigned to the type 'StoresSummaryResults'. The property 'Data' is not present in the 'Observable<any>' type

As a newcomer to using the Observable with Angular 2, I am facing an issue where my structure is not receiving the results despite being able to validate the response from my REST API. Below is the data class in Typescript that I have: import { RESTResul ...